xref: /aosp_15_r20/hardware/interfaces/camera/device/default/ExternalCameraDeviceSession.cpp (revision 4d7e907c777eeecc4c5bd7cf640a754fac206ff7)
1 /*
2  * Copyright (C) 2022 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 "ExtCamDevSsn"
18 // #define LOG_NDEBUG 0
19 #include <log/log.h>
20 
21 #include "ExternalCameraDeviceSession.h"
22 
23 #include <Exif.h>
24 #include <ExternalCameraOfflineSession.h>
25 #include <aidl/android/hardware/camera/device/CameraBlob.h>
26 #include <aidl/android/hardware/camera/device/CameraBlobId.h>
27 #include <aidl/android/hardware/camera/device/ErrorMsg.h>
28 #include <aidl/android/hardware/camera/device/ShutterMsg.h>
29 #include <aidl/android/hardware/camera/device/StreamBufferRet.h>
30 #include <aidl/android/hardware/camera/device/StreamBuffersVal.h>
31 #include <aidl/android/hardware/camera/device/StreamConfigurationMode.h>
32 #include <aidl/android/hardware/camera/device/StreamRotation.h>
33 #include <aidl/android/hardware/camera/device/StreamType.h>
34 #include <aidl/android/hardware/graphics/common/Dataspace.h>
35 #include <aidlcommonsupport/NativeHandle.h>
36 #include <convert.h>
37 #include <linux/videodev2.h>
38 #include <sync/sync.h>
39 #include <utils/Trace.h>
40 #include <deque>
41 
42 #define HAVE_JPEG  // required for libyuv.h to export MJPEG decode APIs
43 #include <libyuv.h>
44 #include <libyuv/convert.h>
45 
46 namespace android {
47 namespace hardware {
48 namespace camera {
49 namespace device {
50 namespace implementation {
51 
52 namespace {
53 
54 // Size of request/result metadata fast message queue. Change to 0 to always use hwbinder buffer.
55 static constexpr size_t kMetadataMsgQueueSize = 1 << 18 /* 256kB */;
56 
57 const int kBadFramesAfterStreamOn = 1;  // drop x frames after streamOn to get rid of some initial
58                                         // bad frames. TODO: develop a better bad frame detection
59                                         // method
60 constexpr int MAX_RETRY = 15;  // Allow retry some ioctl failures a few times to account for some
61                                // webcam showing temporarily ioctl failures.
62 constexpr int IOCTL_RETRY_SLEEP_US = 33000;  // 33ms * MAX_RETRY = 0.5 seconds
63 
64 // Constants for tryLock during dumpstate
65 static constexpr int kDumpLockRetries = 50;
66 static constexpr int kDumpLockSleep = 60000;
67 
tryLock(Mutex & mutex)68 bool tryLock(Mutex& mutex) {
69     bool locked = false;
70     for (int i = 0; i < kDumpLockRetries; ++i) {
71         if (mutex.tryLock() == NO_ERROR) {
72             locked = true;
73             break;
74         }
75         usleep(kDumpLockSleep);
76     }
77     return locked;
78 }
79 
tryLock(std::mutex & mutex)80 bool tryLock(std::mutex& mutex) {
81     bool locked = false;
82     for (int i = 0; i < kDumpLockRetries; ++i) {
83         if (mutex.try_lock()) {
84             locked = true;
85             break;
86         }
87         usleep(kDumpLockSleep);
88     }
89     return locked;
90 }
91 
92 }  // anonymous namespace
93 
94 using ::aidl::android::hardware::camera::device::BufferRequestStatus;
95 using ::aidl::android::hardware::camera::device::CameraBlob;
96 using ::aidl::android::hardware::camera::device::CameraBlobId;
97 using ::aidl::android::hardware::camera::device::ErrorMsg;
98 using ::aidl::android::hardware::camera::device::ShutterMsg;
99 using ::aidl::android::hardware::camera::device::StreamBuffer;
100 using ::aidl::android::hardware::camera::device::StreamBufferRet;
101 using ::aidl::android::hardware::camera::device::StreamBuffersVal;
102 using ::aidl::android::hardware::camera::device::StreamConfigurationMode;
103 using ::aidl::android::hardware::camera::device::StreamRotation;
104 using ::aidl::android::hardware::camera::device::StreamType;
105 using ::aidl::android::hardware::graphics::common::Dataspace;
106 using ::android::hardware::camera::common::V1_0::helper::ExifUtils;
107 
108 // Static instances
109 const int ExternalCameraDeviceSession::kMaxProcessedStream;
110 const int ExternalCameraDeviceSession::kMaxStallStream;
111 HandleImporter ExternalCameraDeviceSession::sHandleImporter;
112 
ExternalCameraDeviceSession(const std::shared_ptr<ICameraDeviceCallback> & callback,const ExternalCameraConfig & cfg,const std::vector<SupportedV4L2Format> & sortedFormats,const CroppingType & croppingType,const common::V1_0::helper::CameraMetadata & chars,const std::string & cameraId,unique_fd v4l2Fd)113 ExternalCameraDeviceSession::ExternalCameraDeviceSession(
114         const std::shared_ptr<ICameraDeviceCallback>& callback, const ExternalCameraConfig& cfg,
115         const std::vector<SupportedV4L2Format>& sortedFormats, const CroppingType& croppingType,
116         const common::V1_0::helper::CameraMetadata& chars, const std::string& cameraId,
117         unique_fd v4l2Fd)
118     : mCallback(callback),
119       mCfg(cfg),
120       mCameraCharacteristics(chars),
121       mSupportedFormats(sortedFormats),
122       mCroppingType(croppingType),
123       mCameraId(cameraId),
124       mV4l2Fd(std::move(v4l2Fd)),
125       mMaxThumbResolution(getMaxThumbResolution()),
126       mMaxJpegResolution(getMaxJpegResolution()) {}
127 
getMaxThumbResolution() const128 Size ExternalCameraDeviceSession::getMaxThumbResolution() const {
129     return getMaxThumbnailResolution(mCameraCharacteristics);
130 }
131 
getMaxJpegResolution() const132 Size ExternalCameraDeviceSession::getMaxJpegResolution() const {
133     Size ret{0, 0};
134     for (auto& fmt : mSupportedFormats) {
135         if (fmt.width * fmt.height > ret.width * ret.height) {
136             ret = Size{fmt.width, fmt.height};
137         }
138     }
139     return ret;
140 }
141 
initialize()142 bool ExternalCameraDeviceSession::initialize() {
143     if (mV4l2Fd.get() < 0) {
144         ALOGE("%s: invalid v4l2 device fd %d!", __FUNCTION__, mV4l2Fd.get());
145         return true;
146     }
147 
148     struct v4l2_capability capability;
149     int ret = ioctl(mV4l2Fd.get(), VIDIOC_QUERYCAP, &capability);
150     std::string make, model;
151     if (ret < 0) {
152         ALOGW("%s v4l2 QUERYCAP failed", __FUNCTION__);
153         mExifMake = "Generic UVC webcam";
154         mExifModel = "Generic UVC webcam";
155     } else {
156         // capability.card is UTF-8 encoded
157         char card[32];
158         int j = 0;
159         for (int i = 0; i < 32; i++) {
160             if (capability.card[i] < 128) {
161                 card[j++] = capability.card[i];
162             }
163             if (capability.card[i] == '\0') {
164                 break;
165             }
166         }
167         if (j == 0 || card[j - 1] != '\0') {
168             mExifMake = "Generic UVC webcam";
169             mExifModel = "Generic UVC webcam";
170         } else {
171             mExifMake = card;
172             mExifModel = card;
173         }
174     }
175 
176     initOutputThread();
177     if (mOutputThread == nullptr) {
178         ALOGE("%s: init OutputThread failed!", __FUNCTION__);
179         return true;
180     }
181     mOutputThread->setExifMakeModel(mExifMake, mExifModel);
182 
183     status_t status = initDefaultRequests();
184     if (status != OK) {
185         ALOGE("%s: init default requests failed!", __FUNCTION__);
186         return true;
187     }
188 
189     mRequestMetadataQueue =
190             std::make_unique<RequestMetadataQueue>(kMetadataMsgQueueSize, false /* non blocking */);
191     if (!mRequestMetadataQueue->isValid()) {
192         ALOGE("%s: invalid request fmq", __FUNCTION__);
193         return true;
194     }
195 
196     mResultMetadataQueue =
197             std::make_shared<ResultMetadataQueue>(kMetadataMsgQueueSize, false /* non blocking */);
198     if (!mResultMetadataQueue->isValid()) {
199         ALOGE("%s: invalid result fmq", __FUNCTION__);
200         return true;
201     }
202 
203     mOutputThread->run();
204     return false;
205 }
206 
isInitFailed()207 bool ExternalCameraDeviceSession::isInitFailed() {
208     Mutex::Autolock _l(mLock);
209     if (!mInitialized) {
210         mInitFail = initialize();
211         mInitialized = true;
212     }
213     return mInitFail;
214 }
215 
initOutputThread()216 void ExternalCameraDeviceSession::initOutputThread() {
217     // Grab a shared_ptr to 'this' from ndk::SharedRefBase::ref()
218     std::shared_ptr<ExternalCameraDeviceSession> thiz = ref<ExternalCameraDeviceSession>();
219 
220     mBufferRequestThread = std::make_shared<BufferRequestThread>(/*parent=*/thiz, mCallback);
221     mBufferRequestThread->run();
222     mOutputThread = std::make_shared<OutputThread>(/*parent=*/thiz, mCroppingType,
223                                                    mCameraCharacteristics, mBufferRequestThread);
224 }
225 
closeOutputThread()226 void ExternalCameraDeviceSession::closeOutputThread() {
227     if (mOutputThread != nullptr) {
228         mOutputThread->flush();
229         mOutputThread->requestExitAndWait();
230         mOutputThread.reset();
231     }
232 }
233 
closeBufferRequestThread()234 void ExternalCameraDeviceSession::closeBufferRequestThread() {
235     if (mBufferRequestThread != nullptr) {
236         mBufferRequestThread->requestExitAndWait();
237         mBufferRequestThread.reset();
238     }
239 }
240 
initStatus() const241 Status ExternalCameraDeviceSession::initStatus() const {
242     Mutex::Autolock _l(mLock);
243     Status status = Status::OK;
244     if (mInitFail || mClosed) {
245         ALOGI("%s: session initFailed %d closed %d", __FUNCTION__, mInitFail, mClosed);
246         status = Status::INTERNAL_ERROR;
247     }
248     return status;
249 }
250 
~ExternalCameraDeviceSession()251 ExternalCameraDeviceSession::~ExternalCameraDeviceSession() {
252     if (!isClosed()) {
253         ALOGE("ExternalCameraDeviceSession deleted before close!");
254         closeImpl();
255     }
256 }
257 
constructDefaultRequestSettings(RequestTemplate in_type,CameraMetadata * _aidl_return)258 ScopedAStatus ExternalCameraDeviceSession::constructDefaultRequestSettings(
259         RequestTemplate in_type, CameraMetadata* _aidl_return) {
260     CameraMetadata emptyMetadata;
261     Status status = initStatus();
262     if (status != Status::OK) {
263         return fromStatus(status);
264     }
265     switch (in_type) {
266         case RequestTemplate::PREVIEW:
267         case RequestTemplate::STILL_CAPTURE:
268         case RequestTemplate::VIDEO_RECORD:
269         case RequestTemplate::VIDEO_SNAPSHOT: {
270             *_aidl_return = mDefaultRequests[in_type];
271             break;
272         }
273         case RequestTemplate::MANUAL:
274         case RequestTemplate::ZERO_SHUTTER_LAG:
275             // Don't support MANUAL, ZSL templates
276             status = Status::ILLEGAL_ARGUMENT;
277             break;
278         default:
279             ALOGE("%s: unknown request template type %d", __FUNCTION__, static_cast<int>(in_type));
280             status = Status::ILLEGAL_ARGUMENT;
281             break;
282     }
283     return fromStatus(status);
284 }
285 
configureStreams(const StreamConfiguration & in_requestedConfiguration,std::vector<HalStream> * _aidl_return)286 ScopedAStatus ExternalCameraDeviceSession::configureStreams(
287         const StreamConfiguration& in_requestedConfiguration,
288         std::vector<HalStream>* _aidl_return) {
289     uint32_t blobBufferSize = 0;
290     _aidl_return->clear();
291     Mutex::Autolock _il(mInterfaceLock);
292 
293     Status status =
294             isStreamCombinationSupported(in_requestedConfiguration, mSupportedFormats, mCfg);
295     if (status != Status::OK) {
296         return fromStatus(status);
297     }
298 
299     status = initStatus();
300     if (status != Status::OK) {
301         return fromStatus(status);
302     }
303 
304     {
305         std::lock_guard<std::mutex> lk(mInflightFramesLock);
306         if (!mInflightFrames.empty()) {
307             ALOGE("%s: trying to configureStreams while there are still %zu inflight frames!",
308                   __FUNCTION__, mInflightFrames.size());
309             return fromStatus(Status::INTERNAL_ERROR);
310         }
311     }
312 
313     Mutex::Autolock _l(mLock);
314     {
315         Mutex::Autolock _cl(mCbsLock);
316         // Add new streams
317         for (const auto& stream : in_requestedConfiguration.streams) {
318             if (mStreamMap.count(stream.id) == 0) {
319                 mStreamMap[stream.id] = stream;
320                 mCirculatingBuffers.emplace(stream.id, CirculatingBuffers{});
321             }
322         }
323 
324         // Cleanup removed streams
325         for (auto it = mStreamMap.begin(); it != mStreamMap.end();) {
326             int id = it->first;
327             bool found = false;
328             for (const auto& stream : in_requestedConfiguration.streams) {
329                 if (id == stream.id) {
330                     found = true;
331                     break;
332                 }
333             }
334             if (!found) {
335                 // Unmap all buffers of deleted stream
336                 cleanupBuffersLocked(id);
337                 it = mStreamMap.erase(it);
338             } else {
339                 ++it;
340             }
341         }
342     }
343 
344     // Now select a V4L2 format to produce all output streams
345     float desiredAr = (mCroppingType == VERTICAL) ? kMaxAspectRatio : kMinAspectRatio;
346     uint32_t maxDim = 0;
347     for (const auto& stream : in_requestedConfiguration.streams) {
348         float aspectRatio = ASPECT_RATIO(stream);
349         ALOGI("%s: request stream %dx%d", __FUNCTION__, stream.width, stream.height);
350         if ((mCroppingType == VERTICAL && aspectRatio < desiredAr) ||
351             (mCroppingType == HORIZONTAL && aspectRatio > desiredAr)) {
352             desiredAr = aspectRatio;
353         }
354 
355         // The dimension that's not cropped
356         uint32_t dim = (mCroppingType == VERTICAL) ? stream.width : stream.height;
357         if (dim > maxDim) {
358             maxDim = dim;
359         }
360     }
361 
362     // Find the smallest format that matches the desired aspect ratio and is wide/high enough
363     SupportedV4L2Format v4l2Fmt{.width = 0, .height = 0};
364     for (const auto& fmt : mSupportedFormats) {
365         uint32_t dim = (mCroppingType == VERTICAL) ? fmt.width : fmt.height;
366         if (dim >= maxDim) {
367             float aspectRatio = ASPECT_RATIO(fmt);
368             if (isAspectRatioClose(aspectRatio, desiredAr)) {
369                 v4l2Fmt = fmt;
370                 // since mSupportedFormats is sorted by width then height, the first matching fmt
371                 // will be the smallest one with matching aspect ratio
372                 break;
373             }
374         }
375     }
376 
377     if (v4l2Fmt.width == 0) {
378         // Cannot find exact good aspect ratio candidate, try to find a close one
379         for (const auto& fmt : mSupportedFormats) {
380             uint32_t dim = (mCroppingType == VERTICAL) ? fmt.width : fmt.height;
381             if (dim >= maxDim) {
382                 float aspectRatio = ASPECT_RATIO(fmt);
383                 if ((mCroppingType == VERTICAL && aspectRatio < desiredAr) ||
384                     (mCroppingType == HORIZONTAL && aspectRatio > desiredAr)) {
385                     v4l2Fmt = fmt;
386                     break;
387                 }
388             }
389         }
390     }
391 
392     if (v4l2Fmt.width == 0) {
393         ALOGE("%s: unable to find a resolution matching (%s at least %d, aspect ratio %f)",
394               __FUNCTION__, (mCroppingType == VERTICAL) ? "width" : "height", maxDim, desiredAr);
395         return fromStatus(Status::ILLEGAL_ARGUMENT);
396     }
397 
398     if (configureV4l2StreamLocked(v4l2Fmt) != 0) {
399         ALOGE("V4L configuration failed!, format:%c%c%c%c, w %d, h %d", v4l2Fmt.fourcc & 0xFF,
400               (v4l2Fmt.fourcc >> 8) & 0xFF, (v4l2Fmt.fourcc >> 16) & 0xFF,
401               (v4l2Fmt.fourcc >> 24) & 0xFF, v4l2Fmt.width, v4l2Fmt.height);
402         return fromStatus(Status::INTERNAL_ERROR);
403     }
404 
405     Size v4lSize = {v4l2Fmt.width, v4l2Fmt.height};
406     Size thumbSize{0, 0};
407     camera_metadata_ro_entry entry =
408             mCameraCharacteristics.find(ANDROID_JPEG_AVAILABLE_THUMBNAIL_SIZES);
409     for (uint32_t i = 0; i < entry.count; i += 2) {
410         Size sz{entry.data.i32[i], entry.data.i32[i + 1]};
411         if (sz.width * sz.height > thumbSize.width * thumbSize.height) {
412             thumbSize = sz;
413         }
414     }
415 
416     if (thumbSize.width * thumbSize.height == 0) {
417         ALOGE("%s: non-zero thumbnail size not available", __FUNCTION__);
418         return fromStatus(Status::INTERNAL_ERROR);
419     }
420 
421     mBlobBufferSize = blobBufferSize;
422     status = mOutputThread->allocateIntermediateBuffers(
423             v4lSize, mMaxThumbResolution, in_requestedConfiguration.streams, blobBufferSize);
424     if (status != Status::OK) {
425         ALOGE("%s: allocating intermediate buffers failed!", __FUNCTION__);
426         return fromStatus(status);
427     }
428 
429     std::vector<HalStream>& out = *_aidl_return;
430     out.resize(in_requestedConfiguration.streams.size());
431     for (size_t i = 0; i < in_requestedConfiguration.streams.size(); i++) {
432         out[i].overrideDataSpace = in_requestedConfiguration.streams[i].dataSpace;
433         out[i].id = in_requestedConfiguration.streams[i].id;
434         // TODO: double check should we add those CAMERA flags
435         mStreamMap[in_requestedConfiguration.streams[i].id].usage = out[i].producerUsage =
436                 static_cast<BufferUsage>(((int64_t)in_requestedConfiguration.streams[i].usage) |
437                                          ((int64_t)BufferUsage::CPU_WRITE_OFTEN) |
438                                          ((int64_t)BufferUsage::CAMERA_OUTPUT));
439         out[i].consumerUsage = static_cast<BufferUsage>(0);
440         out[i].maxBuffers = static_cast<int32_t>(mV4L2BufferCount);
441 
442         switch (in_requestedConfiguration.streams[i].format) {
443             case PixelFormat::BLOB:
444             case PixelFormat::YCBCR_420_888:
445             case PixelFormat::YV12:  // Used by SurfaceTexture
446             case PixelFormat::Y16:
447                 // No override
448                 out[i].overrideFormat = in_requestedConfiguration.streams[i].format;
449                 break;
450             case PixelFormat::IMPLEMENTATION_DEFINED:
451                 // Implementation Defined
452                 // This should look at the Stream's dataspace flag to determine the format or leave
453                 // it as is if the rest of the system knows how to handle a private format. To keep
454                 // this HAL generic, this is being overridden to YUV420
455                 out[i].overrideFormat = PixelFormat::YCBCR_420_888;
456                 // Save overridden format in mStreamMap
457                 mStreamMap[in_requestedConfiguration.streams[i].id].format = out[i].overrideFormat;
458                 break;
459             default:
460                 ALOGE("%s: unsupported format 0x%x", __FUNCTION__,
461                       in_requestedConfiguration.streams[i].format);
462                 return fromStatus(Status::ILLEGAL_ARGUMENT);
463         }
464     }
465 
466     mFirstRequest = true;
467     mLastStreamConfigCounter = in_requestedConfiguration.streamConfigCounter;
468     return fromStatus(Status::OK);
469 }
470 
flush()471 ScopedAStatus ExternalCameraDeviceSession::flush() {
472     ATRACE_CALL();
473     Mutex::Autolock _il(mInterfaceLock);
474     Status status = initStatus();
475     if (status != Status::OK) {
476         return fromStatus(status);
477     }
478     mOutputThread->flush();
479     return fromStatus(Status::OK);
480 }
481 
getCaptureRequestMetadataQueue(MQDescriptor<int8_t,SynchronizedReadWrite> * _aidl_return)482 ScopedAStatus ExternalCameraDeviceSession::getCaptureRequestMetadataQueue(
483         MQDescriptor<int8_t, SynchronizedReadWrite>* _aidl_return) {
484     Mutex::Autolock _il(mInterfaceLock);
485     *_aidl_return = mRequestMetadataQueue->dupeDesc();
486     return fromStatus(Status::OK);
487 }
488 
getCaptureResultMetadataQueue(MQDescriptor<int8_t,SynchronizedReadWrite> * _aidl_return)489 ScopedAStatus ExternalCameraDeviceSession::getCaptureResultMetadataQueue(
490         MQDescriptor<int8_t, SynchronizedReadWrite>* _aidl_return) {
491     Mutex::Autolock _il(mInterfaceLock);
492     *_aidl_return = mResultMetadataQueue->dupeDesc();
493     return fromStatus(Status::OK);
494 }
495 
isReconfigurationRequired(const CameraMetadata & in_oldSessionParams,const CameraMetadata & in_newSessionParams,bool * _aidl_return)496 ScopedAStatus ExternalCameraDeviceSession::isReconfigurationRequired(
497         const CameraMetadata& in_oldSessionParams, const CameraMetadata& in_newSessionParams,
498         bool* _aidl_return) {
499     // reconfiguration required if there is any change in the session params
500     *_aidl_return = in_oldSessionParams != in_newSessionParams;
501     return fromStatus(Status::OK);
502 }
503 
processCaptureRequest(const std::vector<CaptureRequest> & in_requests,const std::vector<BufferCache> & in_cachesToRemove,int32_t * _aidl_return)504 ScopedAStatus ExternalCameraDeviceSession::processCaptureRequest(
505         const std::vector<CaptureRequest>& in_requests,
506         const std::vector<BufferCache>& in_cachesToRemove, int32_t* _aidl_return) {
507     Mutex::Autolock _il(mInterfaceLock);
508     updateBufferCaches(in_cachesToRemove);
509 
510     int32_t& numRequestProcessed = *_aidl_return;
511     numRequestProcessed = 0;
512     Status s = Status::OK;
513     for (size_t i = 0; i < in_requests.size(); i++, numRequestProcessed++) {
514         s = processOneCaptureRequest(in_requests[i]);
515         if (s != Status::OK) {
516             break;
517         }
518     }
519 
520     return fromStatus(s);
521 }
522 
processOneCaptureRequest(const CaptureRequest & request)523 Status ExternalCameraDeviceSession::processOneCaptureRequest(const CaptureRequest& request) {
524     ATRACE_CALL();
525     Status status = initStatus();
526     if (status != Status::OK) {
527         return status;
528     }
529 
530     if (request.inputBuffer.streamId != -1) {
531         ALOGE("%s: external camera does not support reprocessing!", __FUNCTION__);
532         return Status::ILLEGAL_ARGUMENT;
533     }
534 
535     Mutex::Autolock _l(mLock);
536     if (!mV4l2Streaming) {
537         ALOGE("%s: cannot process request in streamOff state!", __FUNCTION__);
538         return Status::INTERNAL_ERROR;
539     }
540 
541     if (request.outputBuffers.empty()) {
542         ALOGE("%s: No output buffers provided.", __FUNCTION__);
543         return Status::ILLEGAL_ARGUMENT;
544     }
545 
546     for (auto& outputBuf : request.outputBuffers) {
547         if (outputBuf.streamId == -1 || mStreamMap.find(outputBuf.streamId) == mStreamMap.end()) {
548             ALOGE("%s: Invalid streamId in CaptureRequest.outputBuffers: %d", __FUNCTION__,
549                   outputBuf.streamId);
550             return Status::ILLEGAL_ARGUMENT;
551         }
552     }
553 
554     const camera_metadata_t* rawSettings = nullptr;
555     bool converted;
556     CameraMetadata settingsFmq;  // settings from FMQ
557 
558     if (request.fmqSettingsSize > 0) {
559         // non-blocking read; client must write metadata before calling
560         // processOneCaptureRequest
561         settingsFmq.metadata.resize(request.fmqSettingsSize);
562         bool read = mRequestMetadataQueue->read(
563                 reinterpret_cast<int8_t*>(settingsFmq.metadata.data()), request.fmqSettingsSize);
564         if (read) {
565             converted = convertFromAidl(settingsFmq, &rawSettings);
566         } else {
567             ALOGE("%s: capture request settings metadata couldn't be read from fmq!", __FUNCTION__);
568             converted = false;
569         }
570     } else {
571         converted = convertFromAidl(request.settings, &rawSettings);
572     }
573 
574     if (converted && rawSettings != nullptr) {
575         mLatestReqSetting = rawSettings;
576     }
577 
578     if (!converted) {
579         ALOGE("%s: capture request settings metadata is corrupt!", __FUNCTION__);
580         return Status::ILLEGAL_ARGUMENT;
581     }
582 
583     if (mFirstRequest && rawSettings == nullptr) {
584         ALOGE("%s: capture request settings must not be null for first request!", __FUNCTION__);
585         return Status::ILLEGAL_ARGUMENT;
586     }
587 
588     size_t numOutputBufs = request.outputBuffers.size();
589 
590     if (numOutputBufs == 0) {
591         ALOGE("%s: capture request must have at least one output buffer!", __FUNCTION__);
592         return Status::ILLEGAL_ARGUMENT;
593     }
594 
595     camera_metadata_entry fpsRange = mLatestReqSetting.find(ANDROID_CONTROL_AE_TARGET_FPS_RANGE);
596     if (fpsRange.count == 2) {
597         double requestFpsMax = fpsRange.data.i32[1];
598         double closestFps = 0.0;
599         double fpsError = 1000.0;
600         bool fpsSupported = false;
601         for (const auto& fr : mV4l2StreamingFmt.frameRates) {
602             double f = fr.getFramesPerSecond();
603             if (std::fabs(requestFpsMax - f) < 1.0) {
604                 fpsSupported = true;
605                 break;
606             }
607             if (std::fabs(requestFpsMax - f) < fpsError) {
608                 fpsError = std::fabs(requestFpsMax - f);
609                 closestFps = f;
610             }
611         }
612         if (!fpsSupported) {
613             /* This can happen in a few scenarios:
614              * 1. The application is sending an FPS range not supported by the configured outputs.
615              * 2. The application is sending a valid FPS range for all configured outputs, but
616              *    the selected V4L2 size can only run at slower speed. This should be very rare
617              *    though: for this to happen a sensor needs to support at least 3 different aspect
618              *    ratio outputs, and when (at least) two outputs are both not the main aspect ratio
619              *    of the webcam, a third size that's larger might be picked and runs into this
620              *    issue.
621              */
622             ALOGW("%s: cannot reach fps %d! Will do %f instead", __FUNCTION__, fpsRange.data.i32[1],
623                   closestFps);
624             requestFpsMax = closestFps;
625         }
626 
627         if (requestFpsMax != mV4l2StreamingFps) {
628             {
629                 std::unique_lock<std::mutex> lk(mV4l2BufferLock);
630                 while (mNumDequeuedV4l2Buffers != 0) {
631                     // Wait until pipeline is idle before reconfigure stream
632                     int waitRet = waitForV4L2BufferReturnLocked(lk);
633                     if (waitRet != 0) {
634                         ALOGE("%s: wait for pipeline idle failed!", __FUNCTION__);
635                         return Status::INTERNAL_ERROR;
636                     }
637                 }
638             }
639             configureV4l2StreamLocked(mV4l2StreamingFmt, requestFpsMax);
640         }
641     }
642 
643     nsecs_t shutterTs = 0;
644     std::unique_ptr<V4L2Frame> frameIn = dequeueV4l2FrameLocked(&shutterTs);
645     if (frameIn == nullptr) {
646         ALOGE("%s: V4L2 deque frame failed!", __FUNCTION__);
647         return Status::INTERNAL_ERROR;
648     }
649 
650     std::shared_ptr<HalRequest> halReq = std::make_shared<HalRequest>();
651     halReq->frameNumber = request.frameNumber;
652     halReq->setting = mLatestReqSetting;
653     halReq->frameIn = std::move(frameIn);
654     halReq->shutterTs = shutterTs;
655     halReq->buffers.resize(numOutputBufs);
656     for (size_t i = 0; i < numOutputBufs; i++) {
657         HalStreamBuffer& halBuf = halReq->buffers[i];
658         int streamId = halBuf.streamId = request.outputBuffers[i].streamId;
659         halBuf.bufferId = request.outputBuffers[i].bufferId;
660         const Stream& stream = mStreamMap[streamId];
661         halBuf.width = stream.width;
662         halBuf.height = stream.height;
663         halBuf.format = stream.format;
664         halBuf.usage = stream.usage;
665         halBuf.bufPtr = nullptr;  // threadloop will request buffer from cameraservice
666         halBuf.acquireFence = 0;  // threadloop will request fence from cameraservice
667         halBuf.fenceTimeout = false;
668     }
669     {
670         std::lock_guard<std::mutex> lk(mInflightFramesLock);
671         mInflightFrames.insert(halReq->frameNumber);
672     }
673     // Send request to OutputThread for the rest of processing
674     mOutputThread->submitRequest(halReq);
675     mFirstRequest = false;
676     return Status::OK;
677 }
678 
signalStreamFlush(const std::vector<int32_t> &,int32_t in_streamConfigCounter)679 ScopedAStatus ExternalCameraDeviceSession::signalStreamFlush(
680         const std::vector<int32_t>& /*in_streamIds*/, int32_t in_streamConfigCounter) {
681     {
682         Mutex::Autolock _l(mLock);
683         if (in_streamConfigCounter < mLastStreamConfigCounter) {
684             // stale call. new streams have been configured since this call was issued.
685             // Do nothing.
686             return fromStatus(Status::OK);
687         }
688     }
689 
690     // TODO: implement if needed.
691     return fromStatus(Status::OK);
692 }
693 
switchToOffline(const std::vector<int32_t> & in_streamsToKeep,CameraOfflineSessionInfo * out_offlineSessionInfo,std::shared_ptr<ICameraOfflineSession> * _aidl_return)694 ScopedAStatus ExternalCameraDeviceSession::switchToOffline(
695         const std::vector<int32_t>& in_streamsToKeep,
696         CameraOfflineSessionInfo* out_offlineSessionInfo,
697         std::shared_ptr<ICameraOfflineSession>* _aidl_return) {
698     std::vector<NotifyMsg> msgs;
699     std::vector<CaptureResult> results;
700     CameraOfflineSessionInfo info;
701     std::shared_ptr<ICameraOfflineSession> session;
702     Status st = switchToOffline(in_streamsToKeep, &msgs, &results, &info, &session);
703 
704     mCallback->notify(msgs);
705     invokeProcessCaptureResultCallback(results, /* tryWriteFmq= */ true);
706     freeReleaseFences(results);
707 
708     // setup return values
709     *out_offlineSessionInfo = info;
710     *_aidl_return = session;
711     return fromStatus(st);
712 }
713 
switchToOffline(const std::vector<int32_t> & offlineStreams,std::vector<NotifyMsg> * msgs,std::vector<CaptureResult> * results,CameraOfflineSessionInfo * info,std::shared_ptr<ICameraOfflineSession> * session)714 Status ExternalCameraDeviceSession::switchToOffline(
715         const std::vector<int32_t>& offlineStreams, std::vector<NotifyMsg>* msgs,
716         std::vector<CaptureResult>* results, CameraOfflineSessionInfo* info,
717         std::shared_ptr<ICameraOfflineSession>* session) {
718     ATRACE_CALL();
719     if (offlineStreams.size() > 1) {
720         ALOGE("%s: more than one offline stream is not supported", __FUNCTION__);
721         return Status::ILLEGAL_ARGUMENT;
722     }
723 
724     if (msgs == nullptr || results == nullptr || info == nullptr || session == nullptr) {
725         ALOGE("%s, output arguments (%p, %p, %p, %p) must not be null", __FUNCTION__, msgs, results,
726               info, session);
727     }
728 
729     Mutex::Autolock _il(mInterfaceLock);
730     Status status = initStatus();
731     if (status != Status::OK) {
732         return status;
733     }
734 
735     Mutex::Autolock _l(mLock);
736     for (auto streamId : offlineStreams) {
737         if (!supportOfflineLocked(streamId)) {
738             return Status::ILLEGAL_ARGUMENT;
739         }
740     }
741 
742     // pause output thread and get all remaining inflight requests
743     auto remainingReqs = mOutputThread->switchToOffline();
744     std::vector<std::shared_ptr<HalRequest>> halReqs;
745 
746     // Send out buffer/request error for remaining requests and filter requests
747     // to be handled in offline mode
748     for (auto& halReq : remainingReqs) {
749         bool dropReq = canDropRequest(offlineStreams, halReq);
750         if (dropReq) {
751             // Request is dropped completely. Just send request error and
752             // there is no need to send the request to offline session
753             processCaptureRequestError(halReq, msgs, results);
754             continue;
755         }
756 
757         // All requests reach here must have at least one offline stream output
758         NotifyMsg shutter;
759         aidl::android::hardware::camera::device::ShutterMsg shutterMsg = {
760                 .frameNumber = static_cast<int32_t>(halReq->frameNumber),
761                 .timestamp = halReq->shutterTs};
762         shutter.set<NotifyMsg::Tag::shutter>(shutterMsg);
763         msgs->push_back(shutter);
764 
765         std::vector<HalStreamBuffer> offlineBuffers;
766         for (const auto& buffer : halReq->buffers) {
767             bool dropBuffer = true;
768             for (auto offlineStreamId : offlineStreams) {
769                 if (buffer.streamId == offlineStreamId) {
770                     dropBuffer = false;
771                     break;
772                 }
773             }
774             if (dropBuffer) {
775                 aidl::android::hardware::camera::device::ErrorMsg errorMsg = {
776                         .frameNumber = static_cast<int32_t>(halReq->frameNumber),
777                         .errorStreamId = buffer.streamId,
778                         .errorCode = ErrorCode::ERROR_BUFFER};
779 
780                 NotifyMsg error;
781                 error.set<NotifyMsg::Tag::error>(errorMsg);
782                 msgs->push_back(error);
783 
784                 results->push_back({
785                         .frameNumber = static_cast<int32_t>(halReq->frameNumber),
786                         .outputBuffers = {},
787                         .inputBuffer = {.streamId = -1},
788                         .partialResult = 0,  // buffer only result
789                 });
790 
791                 CaptureResult& result = results->back();
792                 result.outputBuffers.resize(1);
793                 StreamBuffer& outputBuffer = result.outputBuffers[0];
794                 outputBuffer.streamId = buffer.streamId;
795                 outputBuffer.bufferId = buffer.bufferId;
796                 outputBuffer.status = BufferStatus::ERROR;
797                 if (buffer.acquireFence >= 0) {
798                     native_handle_t* handle = native_handle_create(/*numFds*/ 1, /*numInts*/ 0);
799                     handle->data[0] = buffer.acquireFence;
800                     outputBuffer.releaseFence = android::dupToAidl(handle);
801                     native_handle_delete(handle);
802                 }
803             } else {
804                 offlineBuffers.push_back(buffer);
805             }
806         }
807         halReq->buffers = offlineBuffers;
808         halReqs.push_back(halReq);
809     }
810 
811     // convert hal requests to offline request
812     std::deque<std::shared_ptr<HalRequest>> offlineReqs(halReqs.size());
813     size_t i = 0;
814     for (auto& v4lReq : halReqs) {
815         offlineReqs[i] = std::make_shared<HalRequest>();
816         offlineReqs[i]->frameNumber = v4lReq->frameNumber;
817         offlineReqs[i]->setting = v4lReq->setting;
818         offlineReqs[i]->shutterTs = v4lReq->shutterTs;
819         offlineReqs[i]->buffers = v4lReq->buffers;
820         std::shared_ptr<V4L2Frame> v4l2Frame(static_cast<V4L2Frame*>(v4lReq->frameIn.get()));
821         offlineReqs[i]->frameIn = std::make_shared<AllocatedV4L2Frame>(v4l2Frame);
822         i++;
823         // enqueue V4L2 frame
824         enqueueV4l2Frame(v4l2Frame);
825     }
826 
827     // Collect buffer caches/streams
828     std::vector<Stream> streamInfos(offlineStreams.size());
829     std::map<int, CirculatingBuffers> circulatingBuffers;
830     {
831         Mutex::Autolock _cbsl(mCbsLock);
832         for (auto streamId : offlineStreams) {
833             circulatingBuffers[streamId] = mCirculatingBuffers.at(streamId);
834             mCirculatingBuffers.erase(streamId);
835             streamInfos.push_back(mStreamMap.at(streamId));
836             mStreamMap.erase(streamId);
837         }
838     }
839 
840     fillOfflineSessionInfo(offlineStreams, offlineReqs, circulatingBuffers, info);
841     // create the offline session object
842     bool afTrigger;
843     {
844         std::lock_guard<std::mutex> _lk(mAfTriggerLock);
845         afTrigger = mAfTrigger;
846     }
847 
848     std::shared_ptr<ExternalCameraOfflineSession> sessionImpl =
849             ndk::SharedRefBase::make<ExternalCameraOfflineSession>(
850                     mCroppingType, mCameraCharacteristics, mCameraId, mExifMake, mExifModel,
851                     mBlobBufferSize, afTrigger, streamInfos, offlineReqs, circulatingBuffers);
852 
853     bool initFailed = sessionImpl->initialize();
854     if (initFailed) {
855         ALOGE("%s: offline session initialize failed!", __FUNCTION__);
856         return Status::INTERNAL_ERROR;
857     }
858 
859     // cleanup stream and buffer caches
860     {
861         Mutex::Autolock _cbsl(mCbsLock);
862         for (auto pair : mStreamMap) {
863             cleanupBuffersLocked(/*Stream ID*/ pair.first);
864         }
865         mCirculatingBuffers.clear();
866     }
867     mStreamMap.clear();
868 
869     // update inflight records
870     {
871         std::lock_guard<std::mutex> _lk(mInflightFramesLock);
872         mInflightFrames.clear();
873     }
874 
875     // stop v4l2 streaming
876     if (v4l2StreamOffLocked() != 0) {
877         ALOGE("%s: stop V4L2 streaming failed!", __FUNCTION__);
878         return Status::INTERNAL_ERROR;
879     }
880 
881     // No need to return session if there is no offline requests left
882     if (!offlineReqs.empty()) {
883         *session = sessionImpl;
884     } else {
885         *session = nullptr;
886     }
887 
888     return Status::OK;
889 }
890 
891 #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
892 #define UPDATE(md, tag, data, size)               \
893     do {                                          \
894         if ((md).update((tag), (data), (size))) { \
895             ALOGE("Update " #tag " failed!");     \
896             return BAD_VALUE;                     \
897         }                                         \
898     } while (0)
899 
initDefaultRequests()900 status_t ExternalCameraDeviceSession::initDefaultRequests() {
901     common::V1_0::helper::CameraMetadata md;
902 
903     const uint8_t aberrationMode = ANDROID_COLOR_CORRECTION_ABERRATION_MODE_OFF;
904     UPDATE(md, ANDROID_COLOR_CORRECTION_ABERRATION_MODE, &aberrationMode, 1);
905 
906     const int32_t exposureCompensation = 0;
907     UPDATE(md, ANDROID_CONTROL_AE_EXPOSURE_COMPENSATION, &exposureCompensation, 1);
908 
909     const uint8_t videoStabilizationMode = ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_OFF;
910     UPDATE(md, ANDROID_CONTROL_VIDEO_STABILIZATION_MODE, &videoStabilizationMode, 1);
911 
912     const uint8_t awbMode = ANDROID_CONTROL_AWB_MODE_AUTO;
913     UPDATE(md, ANDROID_CONTROL_AWB_MODE, &awbMode, 1);
914 
915     const uint8_t aeMode = ANDROID_CONTROL_AE_MODE_ON;
916     UPDATE(md, ANDROID_CONTROL_AE_MODE, &aeMode, 1);
917 
918     const uint8_t aePrecaptureTrigger = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE;
919     UPDATE(md, ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER, &aePrecaptureTrigger, 1);
920 
921     const uint8_t afMode = ANDROID_CONTROL_AF_MODE_AUTO;
922     UPDATE(md, ANDROID_CONTROL_AF_MODE, &afMode, 1);
923 
924     const uint8_t afTrigger = ANDROID_CONTROL_AF_TRIGGER_IDLE;
925     UPDATE(md, ANDROID_CONTROL_AF_TRIGGER, &afTrigger, 1);
926 
927     const uint8_t sceneMode = ANDROID_CONTROL_SCENE_MODE_DISABLED;
928     UPDATE(md, ANDROID_CONTROL_SCENE_MODE, &sceneMode, 1);
929 
930     const uint8_t effectMode = ANDROID_CONTROL_EFFECT_MODE_OFF;
931     UPDATE(md, ANDROID_CONTROL_EFFECT_MODE, &effectMode, 1);
932 
933     const uint8_t flashMode = ANDROID_FLASH_MODE_OFF;
934     UPDATE(md, ANDROID_FLASH_MODE, &flashMode, 1);
935 
936     const int32_t thumbnailSize[] = {240, 180};
937     UPDATE(md, ANDROID_JPEG_THUMBNAIL_SIZE, thumbnailSize, 2);
938 
939     const uint8_t jpegQuality = 90;
940     UPDATE(md, ANDROID_JPEG_QUALITY, &jpegQuality, 1);
941     UPDATE(md, ANDROID_JPEG_THUMBNAIL_QUALITY, &jpegQuality, 1);
942 
943     const int32_t jpegOrientation = 0;
944     UPDATE(md, ANDROID_JPEG_ORIENTATION, &jpegOrientation, 1);
945 
946     const uint8_t oisMode = ANDROID_LENS_OPTICAL_STABILIZATION_MODE_OFF;
947     UPDATE(md, ANDROID_LENS_OPTICAL_STABILIZATION_MODE, &oisMode, 1);
948 
949     const uint8_t nrMode = ANDROID_NOISE_REDUCTION_MODE_OFF;
950     UPDATE(md, ANDROID_NOISE_REDUCTION_MODE, &nrMode, 1);
951 
952     const int32_t testPatternModes = ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
953     UPDATE(md, ANDROID_SENSOR_TEST_PATTERN_MODE, &testPatternModes, 1);
954 
955     const uint8_t fdMode = ANDROID_STATISTICS_FACE_DETECT_MODE_OFF;
956     UPDATE(md, ANDROID_STATISTICS_FACE_DETECT_MODE, &fdMode, 1);
957 
958     const uint8_t hotpixelMode = ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE_OFF;
959     UPDATE(md, ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE, &hotpixelMode, 1);
960 
961     bool support30Fps = false;
962     int32_t maxFps = std::numeric_limits<int32_t>::min();
963     for (const auto& supportedFormat : mSupportedFormats) {
964         for (const auto& fr : supportedFormat.frameRates) {
965             int32_t framerateInt = static_cast<int32_t>(fr.getFramesPerSecond());
966             if (maxFps < framerateInt) {
967                 maxFps = framerateInt;
968             }
969             if (framerateInt == 30) {
970                 support30Fps = true;
971                 break;
972             }
973         }
974         if (support30Fps) {
975             break;
976         }
977     }
978 
979     int32_t defaultFramerate = support30Fps ? 30 : maxFps;
980     int32_t defaultFpsRange[] = {defaultFramerate / 2, defaultFramerate};
981     UPDATE(md, ANDROID_CONTROL_AE_TARGET_FPS_RANGE, defaultFpsRange, ARRAY_SIZE(defaultFpsRange));
982 
983     uint8_t antibandingMode = ANDROID_CONTROL_AE_ANTIBANDING_MODE_AUTO;
984     UPDATE(md, ANDROID_CONTROL_AE_ANTIBANDING_MODE, &antibandingMode, 1);
985 
986     const uint8_t controlMode = ANDROID_CONTROL_MODE_AUTO;
987     UPDATE(md, ANDROID_CONTROL_MODE, &controlMode, 1);
988 
989     for (const auto& type : ndk::enum_range<RequestTemplate>()) {
990         common::V1_0::helper::CameraMetadata mdCopy = md;
991         uint8_t intent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW;
992         switch (type) {
993             case RequestTemplate::PREVIEW:
994                 intent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW;
995                 break;
996             case RequestTemplate::STILL_CAPTURE:
997                 intent = ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE;
998                 break;
999             case RequestTemplate::VIDEO_RECORD:
1000                 intent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_RECORD;
1001                 break;
1002             case RequestTemplate::VIDEO_SNAPSHOT:
1003                 intent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_SNAPSHOT;
1004                 break;
1005             default:
1006                 ALOGV("%s: unsupported RequestTemplate type %d", __FUNCTION__, type);
1007                 continue;
1008         }
1009         UPDATE(mdCopy, ANDROID_CONTROL_CAPTURE_INTENT, &intent, 1);
1010         camera_metadata_t* mdPtr = mdCopy.release();
1011         uint8_t* rawMd = reinterpret_cast<uint8_t*>(mdPtr);
1012         CameraMetadata aidlMd;
1013         aidlMd.metadata.assign(rawMd, rawMd + get_camera_metadata_size(mdPtr));
1014         mDefaultRequests[type] = aidlMd;
1015         free_camera_metadata(mdPtr);
1016     }
1017     return OK;
1018 }
1019 
fillCaptureResult(common::V1_0::helper::CameraMetadata & md,nsecs_t timestamp)1020 status_t ExternalCameraDeviceSession::fillCaptureResult(common::V1_0::helper::CameraMetadata& md,
1021                                                         nsecs_t timestamp) {
1022     bool afTrigger = false;
1023     {
1024         std::lock_guard<std::mutex> lk(mAfTriggerLock);
1025         afTrigger = mAfTrigger;
1026         if (md.exists(ANDROID_CONTROL_AF_TRIGGER)) {
1027             camera_metadata_entry entry = md.find(ANDROID_CONTROL_AF_TRIGGER);
1028             if (entry.data.u8[0] == ANDROID_CONTROL_AF_TRIGGER_START) {
1029                 mAfTrigger = afTrigger = true;
1030             } else if (entry.data.u8[0] == ANDROID_CONTROL_AF_TRIGGER_CANCEL) {
1031                 mAfTrigger = afTrigger = false;
1032             }
1033         }
1034     }
1035 
1036     // For USB camera, the USB camera handles everything and we don't have control
1037     // over AF. We only simply fake the AF metadata based on the request
1038     // received here.
1039     uint8_t afState;
1040     if (afTrigger) {
1041         afState = ANDROID_CONTROL_AF_STATE_FOCUSED_LOCKED;
1042     } else {
1043         afState = ANDROID_CONTROL_AF_STATE_INACTIVE;
1044     }
1045     UPDATE(md, ANDROID_CONTROL_AF_STATE, &afState, 1);
1046 
1047     camera_metadata_ro_entry activeArraySize =
1048             mCameraCharacteristics.find(ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE);
1049 
1050     return fillCaptureResultCommon(md, timestamp, activeArraySize);
1051 }
1052 
configureV4l2StreamLocked(const SupportedV4L2Format & v4l2Fmt,double requestFps)1053 int ExternalCameraDeviceSession::configureV4l2StreamLocked(const SupportedV4L2Format& v4l2Fmt,
1054                                                            double requestFps) {
1055     ATRACE_CALL();
1056     int ret = v4l2StreamOffLocked();
1057     if (ret != OK) {
1058         ALOGE("%s: stop v4l2 streaming failed: ret %d", __FUNCTION__, ret);
1059         return ret;
1060     }
1061 
1062     // VIDIOC_S_FMT w/h/fmt
1063     v4l2_format fmt;
1064     fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1065     fmt.fmt.pix.width = v4l2Fmt.width;
1066     fmt.fmt.pix.height = v4l2Fmt.height;
1067     fmt.fmt.pix.pixelformat = v4l2Fmt.fourcc;
1068 
1069     {
1070         int numAttempt = 0;
1071         do {
1072             ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_S_FMT, &fmt));
1073             if (numAttempt == MAX_RETRY) {
1074                 break;
1075             }
1076             numAttempt++;
1077             if (ret < 0) {
1078                 ALOGW("%s: VIDIOC_S_FMT failed, wait 33ms and try again", __FUNCTION__);
1079                 usleep(IOCTL_RETRY_SLEEP_US);  // sleep and try again
1080             }
1081         } while (ret < 0);
1082         if (ret < 0) {
1083             ALOGE("%s: S_FMT ioctl failed: %s", __FUNCTION__, strerror(errno));
1084             return -errno;
1085         }
1086     }
1087 
1088     if (v4l2Fmt.width != fmt.fmt.pix.width || v4l2Fmt.height != fmt.fmt.pix.height ||
1089         v4l2Fmt.fourcc != fmt.fmt.pix.pixelformat) {
1090         ALOGE("%s: S_FMT expect %c%c%c%c %dx%d, got %c%c%c%c %dx%d instead!", __FUNCTION__,
1091               v4l2Fmt.fourcc & 0xFF, (v4l2Fmt.fourcc >> 8) & 0xFF, (v4l2Fmt.fourcc >> 16) & 0xFF,
1092               (v4l2Fmt.fourcc >> 24) & 0xFF, v4l2Fmt.width, v4l2Fmt.height,
1093               fmt.fmt.pix.pixelformat & 0xFF, (fmt.fmt.pix.pixelformat >> 8) & 0xFF,
1094               (fmt.fmt.pix.pixelformat >> 16) & 0xFF, (fmt.fmt.pix.pixelformat >> 24) & 0xFF,
1095               fmt.fmt.pix.width, fmt.fmt.pix.height);
1096         return -EINVAL;
1097     }
1098 
1099     uint32_t bufferSize = fmt.fmt.pix.sizeimage;
1100     ALOGI("%s: V4L2 buffer size is %d", __FUNCTION__, bufferSize);
1101     uint32_t expectedMaxBufferSize = kMaxBytesPerPixel * fmt.fmt.pix.width * fmt.fmt.pix.height;
1102     if ((bufferSize == 0) || (bufferSize > expectedMaxBufferSize)) {
1103         ALOGE("%s: V4L2 buffer size: %u looks invalid. Expected maximum size: %u", __FUNCTION__,
1104               bufferSize, expectedMaxBufferSize);
1105         return -EINVAL;
1106     }
1107     mMaxV4L2BufferSize = bufferSize;
1108 
1109     const double kDefaultFps = 30.0;
1110     double fps = std::numeric_limits<double>::max();
1111     if (requestFps != 0.0) {
1112         fps = requestFps;
1113     } else {
1114         double maxFps = -1.0;
1115         // Try to pick the slowest fps that is at least 30
1116         for (const auto& fr : v4l2Fmt.frameRates) {
1117             double f = fr.getFramesPerSecond();
1118             if (maxFps < f) {
1119                 maxFps = f;
1120             }
1121             if (f >= kDefaultFps && f < fps) {
1122                 fps = f;
1123             }
1124         }
1125         // No fps > 30 found, use the highest fps available within supported formats.
1126         if (fps == std::numeric_limits<double>::max()) {
1127             fps = maxFps;
1128         }
1129     }
1130 
1131     int fpsRet = setV4l2FpsLocked(fps);
1132     if (fpsRet != 0 && fpsRet != -EINVAL) {
1133         ALOGE("%s: set fps failed: %s", __FUNCTION__, strerror(fpsRet));
1134         return fpsRet;
1135     }
1136 
1137     uint32_t v4lBufferCount = (fps >= kDefaultFps) ? mCfg.numVideoBuffers : mCfg.numStillBuffers;
1138 
1139     // Double the max lag in theory.
1140     mMaxLagNs = v4lBufferCount * 1000000000LL * 2 / fps;
1141     ALOGI("%s: set mMaxLagNs to %" PRIu64 " ns, v4lBufferCount %u", __FUNCTION__, mMaxLagNs,
1142           v4lBufferCount);
1143 
1144     // VIDIOC_REQBUFS: create buffers
1145     v4l2_requestbuffers req_buffers{};
1146     req_buffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1147     req_buffers.memory = V4L2_MEMORY_MMAP;
1148     req_buffers.count = v4lBufferCount;
1149     if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_REQBUFS, &req_buffers)) < 0) {
1150         ALOGE("%s: VIDIOC_REQBUFS failed: %s", __FUNCTION__, strerror(errno));
1151         return -errno;
1152     }
1153 
1154     // Driver can indeed return more buffer if it needs more to operate
1155     if (req_buffers.count < v4lBufferCount) {
1156         ALOGE("%s: VIDIOC_REQBUFS expected %d buffers, got %d instead", __FUNCTION__,
1157               v4lBufferCount, req_buffers.count);
1158         return NO_MEMORY;
1159     }
1160 
1161     // VIDIOC_QUERYBUF:  get buffer offset in the V4L2 fd
1162     // VIDIOC_QBUF: send buffer to driver
1163     mV4L2BufferCount = req_buffers.count;
1164     for (uint32_t i = 0; i < req_buffers.count; i++) {
1165         v4l2_buffer buffer = {
1166                 .index = i, .type = V4L2_BUF_TYPE_VIDEO_CAPTURE, .memory = V4L2_MEMORY_MMAP};
1167 
1168         if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QUERYBUF, &buffer)) < 0) {
1169             ALOGE("%s: QUERYBUF %d failed: %s", __FUNCTION__, i, strerror(errno));
1170             return -errno;
1171         }
1172 
1173         if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
1174             ALOGE("%s: QBUF %d failed: %s", __FUNCTION__, i, strerror(errno));
1175             return -errno;
1176         }
1177     }
1178 
1179     {
1180         // VIDIOC_STREAMON: start streaming
1181         v4l2_buf_type capture_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1182         int numAttempt = 0;
1183         do {
1184             ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_STREAMON, &capture_type));
1185             if (numAttempt == MAX_RETRY) {
1186                 break;
1187             }
1188             if (ret < 0) {
1189                 ALOGW("%s: VIDIOC_STREAMON failed, wait 33ms and try again", __FUNCTION__);
1190                 usleep(IOCTL_RETRY_SLEEP_US);  // sleep 100 ms and try again
1191             }
1192         } while (ret < 0);
1193 
1194         if (ret < 0) {
1195             ALOGE("%s: VIDIOC_STREAMON ioctl failed: %s", __FUNCTION__, strerror(errno));
1196             return -errno;
1197         }
1198     }
1199 
1200     // Swallow first few frames after streamOn to account for bad frames from some devices
1201     for (int i = 0; i < kBadFramesAfterStreamOn; i++) {
1202         v4l2_buffer buffer{};
1203         buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1204         buffer.memory = V4L2_MEMORY_MMAP;
1205         if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_DQBUF, &buffer)) < 0) {
1206             ALOGE("%s: DQBUF fails: %s", __FUNCTION__, strerror(errno));
1207             return -errno;
1208         }
1209 
1210         if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
1211             ALOGE("%s: QBUF index %d fails: %s", __FUNCTION__, buffer.index, strerror(errno));
1212             return -errno;
1213         }
1214     }
1215 
1216     ALOGI("%s: start V4L2 streaming %dx%d@%ffps", __FUNCTION__, v4l2Fmt.width, v4l2Fmt.height, fps);
1217     mV4l2StreamingFmt = v4l2Fmt;
1218     mV4l2Streaming = true;
1219     return OK;
1220 }
1221 
dequeueV4l2FrameLocked(nsecs_t * shutterTs)1222 std::unique_ptr<V4L2Frame> ExternalCameraDeviceSession::dequeueV4l2FrameLocked(nsecs_t* shutterTs) {
1223     ATRACE_CALL();
1224     std::unique_ptr<V4L2Frame> ret = nullptr;
1225     if (shutterTs == nullptr) {
1226         ALOGE("%s: shutterTs must not be null!", __FUNCTION__);
1227         return ret;
1228     }
1229 
1230     {
1231         std::unique_lock<std::mutex> lk(mV4l2BufferLock);
1232         if (mNumDequeuedV4l2Buffers == mV4L2BufferCount) {
1233             int waitRet = waitForV4L2BufferReturnLocked(lk);
1234             if (waitRet != 0) {
1235                 return ret;
1236             }
1237         }
1238     }
1239 
1240     uint64_t lagNs = 0;
1241     v4l2_buffer buffer{};
1242     do {
1243         ATRACE_BEGIN("VIDIOC_DQBUF");
1244         buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1245         buffer.memory = V4L2_MEMORY_MMAP;
1246         if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_DQBUF, &buffer)) < 0) {
1247             ALOGE("%s: DQBUF fails: %s", __FUNCTION__, strerror(errno));
1248             return ret;
1249         }
1250         ATRACE_END();
1251 
1252         if (buffer.index >= mV4L2BufferCount) {
1253             ALOGE("%s: Invalid buffer id: %d", __FUNCTION__, buffer.index);
1254             return ret;
1255         }
1256 
1257         if (buffer.flags & V4L2_BUF_FLAG_ERROR) {
1258             ALOGE("%s: v4l2 buf error! buf flag 0x%x", __FUNCTION__, buffer.flags);
1259             // TODO: try to dequeue again
1260         }
1261 
1262         if (buffer.bytesused > mMaxV4L2BufferSize) {
1263             ALOGE("%s: v4l2 buffer bytes used: %u maximum %u", __FUNCTION__, buffer.bytesused,
1264                   mMaxV4L2BufferSize);
1265             return ret;
1266         }
1267 
1268         nsecs_t curTimeNs = systemTime(SYSTEM_TIME_MONOTONIC);
1269 
1270         if (buffer.flags & V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC) {
1271             // Ideally we should also check for V4L2_BUF_FLAG_TSTAMP_SRC_SOE, but
1272             // even V4L2_BUF_FLAG_TSTAMP_SRC_EOF is better than capture a timestamp now
1273             *shutterTs = static_cast<nsecs_t>(buffer.timestamp.tv_sec) * 1000000000LL +
1274                          buffer.timestamp.tv_usec * 1000LL;
1275         } else {
1276             *shutterTs = curTimeNs;
1277         }
1278 
1279         // The tactic only takes effect on v4l2 buffers with flag V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC.
1280         // Most USB cameras should have the feature.
1281         if (curTimeNs < *shutterTs) {
1282             lagNs = 0;
1283             ALOGW("%s: should not happen, the monotonic clock has issue, shutterTs is in the "
1284                   "future, curTimeNs %" PRId64 "  < "
1285                   "shutterTs %" PRId64 "",
1286                   __func__, curTimeNs, *shutterTs);
1287         } else {
1288             lagNs = curTimeNs - *shutterTs;
1289         }
1290 
1291         if (lagNs > mMaxLagNs) {
1292             ALOGI("%s: drop too old buffer, index %d, lag %" PRIu64 " ns > max %" PRIu64 " ns", __FUNCTION__,
1293                   buffer.index, lagNs, mMaxLagNs);
1294             int retVal = ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer);
1295             if (retVal) {
1296                 ALOGE("%s: unexpected VIDIOC_QBUF failed, retVal %d", __FUNCTION__, retVal);
1297                 return ret;
1298             }
1299         }
1300     } while (lagNs > mMaxLagNs);
1301 
1302     {
1303         std::lock_guard<std::mutex> lk(mV4l2BufferLock);
1304         mNumDequeuedV4l2Buffers++;
1305     }
1306 
1307     return std::make_unique<V4L2Frame>(mV4l2StreamingFmt.width, mV4l2StreamingFmt.height,
1308                                        mV4l2StreamingFmt.fourcc, buffer.index, mV4l2Fd.get(),
1309                                        buffer.bytesused, buffer.m.offset);
1310 }
1311 
enqueueV4l2Frame(const std::shared_ptr<V4L2Frame> & frame)1312 void ExternalCameraDeviceSession::enqueueV4l2Frame(const std::shared_ptr<V4L2Frame>& frame) {
1313     ATRACE_CALL();
1314     frame->unmap();
1315     ATRACE_BEGIN("VIDIOC_QBUF");
1316     v4l2_buffer buffer{};
1317     buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1318     buffer.memory = V4L2_MEMORY_MMAP;
1319     buffer.index = frame->mBufferIndex;
1320     if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
1321         ALOGE("%s: QBUF index %d fails: %s", __FUNCTION__, frame->mBufferIndex, strerror(errno));
1322         return;
1323     }
1324     ATRACE_END();
1325 
1326     {
1327         std::lock_guard<std::mutex> lk(mV4l2BufferLock);
1328         mNumDequeuedV4l2Buffers--;
1329     }
1330     mV4L2BufferReturned.notify_one();
1331 }
1332 
isSupported(const Stream & stream,const std::vector<SupportedV4L2Format> & supportedFormats,const ExternalCameraConfig & devCfg)1333 bool ExternalCameraDeviceSession::isSupported(
1334         const Stream& stream, const std::vector<SupportedV4L2Format>& supportedFormats,
1335         const ExternalCameraConfig& devCfg) {
1336     Dataspace ds = stream.dataSpace;
1337     PixelFormat fmt = stream.format;
1338     uint32_t width = stream.width;
1339     uint32_t height = stream.height;
1340     // TODO: check usage flags
1341 
1342     if (stream.streamType != StreamType::OUTPUT) {
1343         ALOGE("%s: does not support non-output stream type", __FUNCTION__);
1344         return false;
1345     }
1346 
1347     if (stream.rotation != StreamRotation::ROTATION_0) {
1348         ALOGE("%s: does not support stream rotation", __FUNCTION__);
1349         return false;
1350     }
1351 
1352     switch (fmt) {
1353         case PixelFormat::BLOB:
1354             if (ds != Dataspace::JFIF) {
1355                 ALOGI("%s: BLOB format does not support dataSpace %x", __FUNCTION__, ds);
1356                 return false;
1357             }
1358             break;
1359         case PixelFormat::IMPLEMENTATION_DEFINED:
1360         case PixelFormat::YCBCR_420_888:
1361         case PixelFormat::YV12:
1362             // TODO: check what dataspace we can support here.
1363             // intentional no-ops.
1364             break;
1365         case PixelFormat::Y16:
1366             if (!devCfg.depthEnabled) {
1367                 ALOGI("%s: Depth is not Enabled", __FUNCTION__);
1368                 return false;
1369             }
1370             if (!(static_cast<int32_t>(ds) & static_cast<int32_t>(Dataspace::DEPTH))) {
1371                 ALOGI("%s: Y16 supports only dataSpace DEPTH", __FUNCTION__);
1372                 return false;
1373             }
1374             break;
1375         default:
1376             ALOGI("%s: does not support format %x", __FUNCTION__, fmt);
1377             return false;
1378     }
1379 
1380     // Assume we can convert any V4L2 format to any of supported output format for now, i.e.
1381     // ignoring v4l2Fmt.fourcc for now. Might need more subtle check if we support more v4l format
1382     // in the futrue.
1383     for (const auto& v4l2Fmt : supportedFormats) {
1384         if (width == v4l2Fmt.width && height == v4l2Fmt.height) {
1385             return true;
1386         }
1387     }
1388     ALOGI("%s: resolution %dx%d is not supported", __FUNCTION__, width, height);
1389     return false;
1390 }
1391 
importBuffer(int32_t streamId,uint64_t bufId,buffer_handle_t buf,buffer_handle_t ** outBufPtr)1392 Status ExternalCameraDeviceSession::importBuffer(int32_t streamId, uint64_t bufId,
1393                                                  buffer_handle_t buf,
1394                                                  /*out*/ buffer_handle_t** outBufPtr) {
1395     Mutex::Autolock _l(mCbsLock);
1396     return importBufferLocked(streamId, bufId, buf, outBufPtr);
1397 }
1398 
importBufferLocked(int32_t streamId,uint64_t bufId,buffer_handle_t buf,buffer_handle_t ** outBufPtr)1399 Status ExternalCameraDeviceSession::importBufferLocked(int32_t streamId, uint64_t bufId,
1400                                                        buffer_handle_t buf,
1401                                                        buffer_handle_t** outBufPtr) {
1402     return importBufferImpl(mCirculatingBuffers, sHandleImporter, streamId, bufId, buf, outBufPtr);
1403 }
1404 
close()1405 ScopedAStatus ExternalCameraDeviceSession::close() {
1406     closeImpl();
1407     return fromStatus(Status::OK);
1408 }
1409 
closeImpl()1410 void ExternalCameraDeviceSession::closeImpl() {
1411     Mutex::Autolock _il(mInterfaceLock);
1412     bool closed = isClosed();
1413     if (!closed) {
1414         closeOutputThread();
1415         closeBufferRequestThread();
1416 
1417         Mutex::Autolock _l(mLock);
1418         // free all buffers
1419         {
1420             Mutex::Autolock _cbsl(mCbsLock);
1421             for (auto pair : mStreamMap) {
1422                 cleanupBuffersLocked(/*Stream ID*/ pair.first);
1423             }
1424         }
1425         v4l2StreamOffLocked();
1426         ALOGV("%s: closing V4L2 camera FD %d", __FUNCTION__, mV4l2Fd.get());
1427         mV4l2Fd.reset();
1428         mClosed = true;
1429     }
1430 }
1431 
isClosed()1432 bool ExternalCameraDeviceSession::isClosed() {
1433     Mutex::Autolock _l(mLock);
1434     return mClosed;
1435 }
1436 
repeatingRequestEnd(int32_t,const std::vector<int32_t> &)1437 ScopedAStatus ExternalCameraDeviceSession::repeatingRequestEnd(
1438         int32_t /*in_frameNumber*/, const std::vector<int32_t>& /*in_streamIds*/) {
1439     // TODO: Figure this one out.
1440     return fromStatus(Status::OK);
1441 }
1442 
v4l2StreamOffLocked()1443 int ExternalCameraDeviceSession::v4l2StreamOffLocked() {
1444     if (!mV4l2Streaming) {
1445         return OK;
1446     }
1447 
1448     {
1449         std::lock_guard<std::mutex> lk(mV4l2BufferLock);
1450         if (mNumDequeuedV4l2Buffers != 0) {
1451             ALOGE("%s: there are %zu inflight V4L buffers", __FUNCTION__, mNumDequeuedV4l2Buffers);
1452             return -1;
1453         }
1454     }
1455     mV4L2BufferCount = 0;
1456 
1457     // VIDIOC_STREAMOFF
1458     v4l2_buf_type capture_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1459     if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_STREAMOFF, &capture_type)) < 0) {
1460         ALOGE("%s: STREAMOFF failed: %s", __FUNCTION__, strerror(errno));
1461         return -errno;
1462     }
1463 
1464     // VIDIOC_REQBUFS: clear buffers
1465     v4l2_requestbuffers req_buffers{};
1466     req_buffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1467     req_buffers.memory = V4L2_MEMORY_MMAP;
1468     req_buffers.count = 0;
1469     if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_REQBUFS, &req_buffers)) < 0) {
1470         ALOGE("%s: REQBUFS failed: %s", __FUNCTION__, strerror(errno));
1471         return -errno;
1472     }
1473 
1474     mV4l2Streaming = false;
1475     return OK;
1476 }
1477 
setV4l2FpsLocked(double fps)1478 int ExternalCameraDeviceSession::setV4l2FpsLocked(double fps) {
1479     // VIDIOC_G_PARM/VIDIOC_S_PARM: set fps
1480     v4l2_streamparm streamparm = {.type = V4L2_BUF_TYPE_VIDEO_CAPTURE};
1481     // The following line checks that the driver knows about framerate get/set.
1482     int ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_G_PARM, &streamparm));
1483     if (ret != 0) {
1484         if (errno == -EINVAL) {
1485             ALOGW("%s: device does not support VIDIOC_G_PARM", __FUNCTION__);
1486         }
1487         return -errno;
1488     }
1489     // Now check if the device is able to accept a capture framerate set.
1490     if (!(streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME)) {
1491         ALOGW("%s: device does not support V4L2_CAP_TIMEPERFRAME", __FUNCTION__);
1492         return -EINVAL;
1493     }
1494 
1495     // fps is float, approximate by a fraction.
1496     const int kFrameRatePrecision = 10000;
1497     streamparm.parm.capture.timeperframe.numerator = kFrameRatePrecision;
1498     streamparm.parm.capture.timeperframe.denominator = (fps * kFrameRatePrecision);
1499 
1500     if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_S_PARM, &streamparm)) < 0) {
1501         ALOGE("%s: failed to set framerate to %f: %s", __FUNCTION__, fps, strerror(errno));
1502         return -1;
1503     }
1504 
1505     double retFps = streamparm.parm.capture.timeperframe.denominator /
1506                     static_cast<double>(streamparm.parm.capture.timeperframe.numerator);
1507     if (std::fabs(fps - retFps) > 1.0) {
1508         ALOGE("%s: expect fps %f, got %f instead", __FUNCTION__, fps, retFps);
1509         return -1;
1510     }
1511     mV4l2StreamingFps = fps;
1512     return 0;
1513 }
1514 
cleanupInflightFences(std::vector<int> & allFences,size_t numFences)1515 void ExternalCameraDeviceSession::cleanupInflightFences(std::vector<int>& allFences,
1516                                                         size_t numFences) {
1517     for (size_t j = 0; j < numFences; j++) {
1518         sHandleImporter.closeFence(allFences[j]);
1519     }
1520 }
1521 
cleanupBuffersLocked(int id)1522 void ExternalCameraDeviceSession::cleanupBuffersLocked(int id) {
1523     for (auto& pair : mCirculatingBuffers.at(id)) {
1524         sHandleImporter.freeBuffer(pair.second);
1525     }
1526     mCirculatingBuffers[id].clear();
1527     mCirculatingBuffers.erase(id);
1528 }
1529 
notifyShutter(int32_t frameNumber,nsecs_t shutterTs)1530 void ExternalCameraDeviceSession::notifyShutter(int32_t frameNumber, nsecs_t shutterTs) {
1531     NotifyMsg msg;
1532     msg.set<NotifyMsg::Tag::shutter>(ShutterMsg{
1533             .frameNumber = frameNumber,
1534             .timestamp = shutterTs,
1535     });
1536     mCallback->notify({msg});
1537 }
notifyError(int32_t frameNumber,int32_t streamId,ErrorCode ec)1538 void ExternalCameraDeviceSession::notifyError(int32_t frameNumber, int32_t streamId, ErrorCode ec) {
1539     NotifyMsg msg;
1540     msg.set<NotifyMsg::Tag::error>(ErrorMsg{
1541             .frameNumber = frameNumber,
1542             .errorStreamId = streamId,
1543             .errorCode = ec,
1544     });
1545     mCallback->notify({msg});
1546 }
1547 
invokeProcessCaptureResultCallback(std::vector<CaptureResult> & results,bool tryWriteFmq)1548 void ExternalCameraDeviceSession::invokeProcessCaptureResultCallback(
1549         std::vector<CaptureResult>& results, bool tryWriteFmq) {
1550     if (mProcessCaptureResultLock.tryLock() != OK) {
1551         const nsecs_t NS_TO_SECOND = 1000000000;
1552         ALOGV("%s: previous call is not finished! waiting 1s...", __FUNCTION__);
1553         if (mProcessCaptureResultLock.timedLock(/* 1s */ NS_TO_SECOND) != OK) {
1554             ALOGE("%s: cannot acquire lock in 1s, cannot proceed", __FUNCTION__);
1555             return;
1556         }
1557     }
1558     if (tryWriteFmq && mResultMetadataQueue->availableToWrite() > 0) {
1559         for (CaptureResult& result : results) {
1560             CameraMetadata& md = result.result;
1561             if (!md.metadata.empty()) {
1562                 if (mResultMetadataQueue->write(reinterpret_cast<int8_t*>(md.metadata.data()),
1563                                                 md.metadata.size())) {
1564                     result.fmqResultSize = md.metadata.size();
1565                     md.metadata.resize(0);
1566                 } else {
1567                     ALOGW("%s: couldn't utilize fmq, fall back to hwbinder", __FUNCTION__);
1568                     result.fmqResultSize = 0;
1569                 }
1570             } else {
1571                 result.fmqResultSize = 0;
1572             }
1573         }
1574     }
1575     auto status = mCallback->processCaptureResult(results);
1576     if (!status.isOk()) {
1577         ALOGE("%s: processCaptureResult ERROR : %d:%d", __FUNCTION__, status.getExceptionCode(),
1578               status.getServiceSpecificError());
1579     }
1580 
1581     mProcessCaptureResultLock.unlock();
1582 }
1583 
waitForV4L2BufferReturnLocked(std::unique_lock<std::mutex> & lk)1584 int ExternalCameraDeviceSession::waitForV4L2BufferReturnLocked(std::unique_lock<std::mutex>& lk) {
1585     ATRACE_CALL();
1586     auto timeout = std::chrono::seconds(kBufferWaitTimeoutSec);
1587     mLock.unlock();
1588     auto st = mV4L2BufferReturned.wait_for(lk, timeout);
1589     // Here we introduce an order where mV4l2BufferLock is acquired before mLock, while
1590     // the normal lock acquisition order is reversed. This is fine because in most of
1591     // cases we are protected by mInterfaceLock. The only thread that can cause deadlock
1592     // is the OutputThread, where we do need to make sure we don't acquire mLock then
1593     // mV4l2BufferLock
1594     mLock.lock();
1595     if (st == std::cv_status::timeout) {
1596         ALOGE("%s: wait for V4L2 buffer return timeout!", __FUNCTION__);
1597         return -1;
1598     }
1599     return 0;
1600 }
1601 
supportOfflineLocked(int32_t streamId)1602 bool ExternalCameraDeviceSession::supportOfflineLocked(int32_t streamId) {
1603     const Stream& stream = mStreamMap[streamId];
1604     if (stream.format == PixelFormat::BLOB &&
1605         static_cast<int32_t>(stream.dataSpace) == static_cast<int32_t>(Dataspace::JFIF)) {
1606         return true;
1607     }
1608     // TODO: support YUV output stream?
1609     return false;
1610 }
1611 
canDropRequest(const std::vector<int32_t> & offlineStreams,std::shared_ptr<HalRequest> halReq)1612 bool ExternalCameraDeviceSession::canDropRequest(const std::vector<int32_t>& offlineStreams,
1613                                                  std::shared_ptr<HalRequest> halReq) {
1614     for (const auto& buffer : halReq->buffers) {
1615         for (auto offlineStreamId : offlineStreams) {
1616             if (buffer.streamId == offlineStreamId) {
1617                 return false;
1618             }
1619         }
1620     }
1621     // Only drop a request completely if it has no offline output
1622     return true;
1623 }
1624 
fillOfflineSessionInfo(const std::vector<int32_t> & offlineStreams,std::deque<std::shared_ptr<HalRequest>> & offlineReqs,const std::map<int,CirculatingBuffers> & circulatingBuffers,CameraOfflineSessionInfo * info)1625 void ExternalCameraDeviceSession::fillOfflineSessionInfo(
1626         const std::vector<int32_t>& offlineStreams,
1627         std::deque<std::shared_ptr<HalRequest>>& offlineReqs,
1628         const std::map<int, CirculatingBuffers>& circulatingBuffers,
1629         CameraOfflineSessionInfo* info) {
1630     if (info == nullptr) {
1631         ALOGE("%s: output info must not be null!", __FUNCTION__);
1632         return;
1633     }
1634 
1635     info->offlineStreams.resize(offlineStreams.size());
1636     info->offlineRequests.resize(offlineReqs.size());
1637 
1638     // Fill in offline reqs and count outstanding buffers
1639     for (size_t i = 0; i < offlineReqs.size(); i++) {
1640         info->offlineRequests[i].frameNumber = offlineReqs[i]->frameNumber;
1641         info->offlineRequests[i].pendingStreams.resize(offlineReqs[i]->buffers.size());
1642         for (size_t bIdx = 0; bIdx < offlineReqs[i]->buffers.size(); bIdx++) {
1643             int32_t streamId = offlineReqs[i]->buffers[bIdx].streamId;
1644             info->offlineRequests[i].pendingStreams[bIdx] = streamId;
1645         }
1646     }
1647 
1648     for (size_t i = 0; i < offlineStreams.size(); i++) {
1649         int32_t streamId = offlineStreams[i];
1650         info->offlineStreams[i].id = streamId;
1651         // outstanding buffers are 0 since we are doing hal buffer management and
1652         // offline session will ask for those buffers later
1653         info->offlineStreams[i].numOutstandingBuffers = 0;
1654         const CirculatingBuffers& bufIdMap = circulatingBuffers.at(streamId);
1655         info->offlineStreams[i].circulatingBufferIds.resize(bufIdMap.size());
1656         size_t bIdx = 0;
1657         for (const auto& pair : bufIdMap) {
1658             // Fill in bufferId
1659             info->offlineStreams[i].circulatingBufferIds[bIdx++] = pair.first;
1660         }
1661     }
1662 }
1663 
isStreamCombinationSupported(const StreamConfiguration & config,const std::vector<SupportedV4L2Format> & supportedFormats,const ExternalCameraConfig & devCfg)1664 Status ExternalCameraDeviceSession::isStreamCombinationSupported(
1665         const StreamConfiguration& config, const std::vector<SupportedV4L2Format>& supportedFormats,
1666         const ExternalCameraConfig& devCfg) {
1667     if (config.operationMode != StreamConfigurationMode::NORMAL_MODE) {
1668         ALOGE("%s: unsupported operation mode: %d", __FUNCTION__, config.operationMode);
1669         return Status::ILLEGAL_ARGUMENT;
1670     }
1671 
1672     if (config.streams.size() == 0) {
1673         ALOGE("%s: cannot configure zero stream", __FUNCTION__);
1674         return Status::ILLEGAL_ARGUMENT;
1675     }
1676 
1677     int numProcessedStream = 0;
1678     int numStallStream = 0;
1679     for (const auto& stream : config.streams) {
1680         // Check if the format/width/height combo is supported
1681         if (!isSupported(stream, supportedFormats, devCfg)) {
1682             return Status::ILLEGAL_ARGUMENT;
1683         }
1684         if (stream.format == PixelFormat::BLOB) {
1685             numStallStream++;
1686         } else {
1687             numProcessedStream++;
1688         }
1689     }
1690 
1691     if (numProcessedStream > kMaxProcessedStream) {
1692         ALOGE("%s: too many processed streams (expect <= %d, got %d)", __FUNCTION__,
1693               kMaxProcessedStream, numProcessedStream);
1694         return Status::ILLEGAL_ARGUMENT;
1695     }
1696 
1697     if (numStallStream > kMaxStallStream) {
1698         ALOGE("%s: too many stall streams (expect <= %d, got %d)", __FUNCTION__, kMaxStallStream,
1699               numStallStream);
1700         return Status::ILLEGAL_ARGUMENT;
1701     }
1702 
1703     return Status::OK;
1704 }
updateBufferCaches(const std::vector<BufferCache> & cachesToRemove)1705 void ExternalCameraDeviceSession::updateBufferCaches(
1706         const std::vector<BufferCache>& cachesToRemove) {
1707     Mutex::Autolock _l(mCbsLock);
1708     for (auto& cache : cachesToRemove) {
1709         auto cbsIt = mCirculatingBuffers.find(cache.streamId);
1710         if (cbsIt == mCirculatingBuffers.end()) {
1711             // The stream could have been removed
1712             continue;
1713         }
1714         CirculatingBuffers& cbs = cbsIt->second;
1715         auto it = cbs.find(cache.bufferId);
1716         if (it != cbs.end()) {
1717             sHandleImporter.freeBuffer(it->second);
1718             cbs.erase(it);
1719         } else {
1720             ALOGE("%s: stream %d buffer %" PRIu64 " is not cached", __FUNCTION__, cache.streamId,
1721                   cache.bufferId);
1722         }
1723     }
1724 }
1725 
processCaptureRequestError(const std::shared_ptr<HalRequest> & req,std::vector<NotifyMsg> * outMsgs,std::vector<CaptureResult> * outResults)1726 Status ExternalCameraDeviceSession::processCaptureRequestError(
1727         const std::shared_ptr<HalRequest>& req, std::vector<NotifyMsg>* outMsgs,
1728         std::vector<CaptureResult>* outResults) {
1729     ATRACE_CALL();
1730     // Return V4L2 buffer to V4L2 buffer queue
1731     std::shared_ptr<V4L2Frame> v4l2Frame = std::static_pointer_cast<V4L2Frame>(req->frameIn);
1732     enqueueV4l2Frame(v4l2Frame);
1733 
1734     if (outMsgs == nullptr) {
1735         notifyShutter(req->frameNumber, req->shutterTs);
1736         notifyError(/*frameNum*/ req->frameNumber, /*stream*/ -1, ErrorCode::ERROR_REQUEST);
1737     } else {
1738         NotifyMsg shutter;
1739         shutter.set<NotifyMsg::Tag::shutter>(
1740                 ShutterMsg{.frameNumber = req->frameNumber, .timestamp = req->shutterTs});
1741 
1742         NotifyMsg error;
1743         error.set<NotifyMsg::Tag::error>(ErrorMsg{.frameNumber = req->frameNumber,
1744                                                   .errorStreamId = -1,
1745                                                   .errorCode = ErrorCode::ERROR_REQUEST});
1746         outMsgs->push_back(shutter);
1747         outMsgs->push_back(error);
1748     }
1749 
1750     // Fill output buffers
1751     CaptureResult result;
1752     result.frameNumber = req->frameNumber;
1753     result.partialResult = 1;
1754     result.inputBuffer.streamId = -1;
1755     result.outputBuffers.resize(req->buffers.size());
1756     for (size_t i = 0; i < req->buffers.size(); i++) {
1757         result.outputBuffers[i].streamId = req->buffers[i].streamId;
1758         result.outputBuffers[i].bufferId = req->buffers[i].bufferId;
1759         result.outputBuffers[i].status = BufferStatus::ERROR;
1760         if (req->buffers[i].acquireFence >= 0) {
1761             // numFds = 0 for error
1762             native_handle_t* handle = native_handle_create(/*numFds*/ 0, /*numInts*/ 0);
1763             result.outputBuffers[i].releaseFence = android::dupToAidl(handle);
1764             native_handle_delete(handle);
1765         }
1766     }
1767 
1768     // update inflight records
1769     {
1770         std::lock_guard<std::mutex> lk(mInflightFramesLock);
1771         mInflightFrames.erase(req->frameNumber);
1772     }
1773 
1774     if (outResults == nullptr) {
1775         // Callback into framework
1776         std::vector<CaptureResult> results(1);
1777         results[0] = std::move(result);
1778         invokeProcessCaptureResultCallback(results, /* tryWriteFmq */ true);
1779         freeReleaseFences(results);
1780     } else {
1781         outResults->push_back(std::move(result));
1782     }
1783     return Status::OK;
1784 }
1785 
processCaptureResult(std::shared_ptr<HalRequest> & req)1786 Status ExternalCameraDeviceSession::processCaptureResult(std::shared_ptr<HalRequest>& req) {
1787     ATRACE_CALL();
1788     // Return V4L2 buffer to V4L2 buffer queue
1789     std::shared_ptr<V4L2Frame> v4l2Frame = std::static_pointer_cast<V4L2Frame>(req->frameIn);
1790     enqueueV4l2Frame(v4l2Frame);
1791 
1792     // NotifyShutter
1793     notifyShutter(req->frameNumber, req->shutterTs);
1794 
1795     // Fill output buffers;
1796     std::vector<CaptureResult> results(1);
1797     CaptureResult& result = results[0];
1798     result.frameNumber = req->frameNumber;
1799     result.partialResult = 1;
1800     result.inputBuffer.streamId = -1;
1801     result.outputBuffers.resize(req->buffers.size());
1802     for (size_t i = 0; i < req->buffers.size(); i++) {
1803         result.outputBuffers[i].streamId = req->buffers[i].streamId;
1804         result.outputBuffers[i].bufferId = req->buffers[i].bufferId;
1805         if (req->buffers[i].fenceTimeout) {
1806             result.outputBuffers[i].status = BufferStatus::ERROR;
1807             if (req->buffers[i].acquireFence >= 0) {
1808                 native_handle_t* handle = native_handle_create(/*numFds*/ 1, /*numInts*/ 0);
1809                 handle->data[0] = req->buffers[i].acquireFence;
1810                 result.outputBuffers[i].releaseFence = android::dupToAidl(handle);
1811                 native_handle_delete(handle);
1812             }
1813             notifyError(req->frameNumber, req->buffers[i].streamId, ErrorCode::ERROR_BUFFER);
1814         } else {
1815             result.outputBuffers[i].status = BufferStatus::OK;
1816             // TODO: refactor
1817             if (req->buffers[i].acquireFence >= 0) {
1818                 native_handle_t* handle = native_handle_create(/*numFds*/ 1, /*numInts*/ 0);
1819                 handle->data[0] = req->buffers[i].acquireFence;
1820                 result.outputBuffers[i].releaseFence = android::dupToAidl(handle);
1821                 native_handle_delete(handle);
1822             }
1823         }
1824     }
1825 
1826     // Fill capture result metadata
1827     fillCaptureResult(req->setting, req->shutterTs);
1828     const camera_metadata_t* rawResult = req->setting.getAndLock();
1829     convertToAidl(rawResult, &result.result);
1830     req->setting.unlock(rawResult);
1831 
1832     // update inflight records
1833     {
1834         std::lock_guard<std::mutex> lk(mInflightFramesLock);
1835         mInflightFrames.erase(req->frameNumber);
1836     }
1837 
1838     // Callback into framework
1839     invokeProcessCaptureResultCallback(results, /* tryWriteFmq */ true);
1840     freeReleaseFences(results);
1841     return Status::OK;
1842 }
1843 
getJpegBufferSize(int32_t width,int32_t height) const1844 ssize_t ExternalCameraDeviceSession::getJpegBufferSize(int32_t width, int32_t height) const {
1845     // Constant from camera3.h
1846     const ssize_t kMinJpegBufferSize = 256 * 1024 + sizeof(CameraBlob);
1847     // Get max jpeg size (area-wise).
1848     if (mMaxJpegResolution.width == 0) {
1849         ALOGE("%s: No supported JPEG stream", __FUNCTION__);
1850         return BAD_VALUE;
1851     }
1852 
1853     // Get max jpeg buffer size
1854     ssize_t maxJpegBufferSize = 0;
1855     camera_metadata_ro_entry jpegBufMaxSize = mCameraCharacteristics.find(ANDROID_JPEG_MAX_SIZE);
1856     if (jpegBufMaxSize.count == 0) {
1857         ALOGE("%s: Can't find maximum JPEG size in static metadata!", __FUNCTION__);
1858         return BAD_VALUE;
1859     }
1860     maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
1861 
1862     if (maxJpegBufferSize <= kMinJpegBufferSize) {
1863         ALOGE("%s: ANDROID_JPEG_MAX_SIZE (%zd) <= kMinJpegBufferSize (%zd)", __FUNCTION__,
1864               maxJpegBufferSize, kMinJpegBufferSize);
1865         return BAD_VALUE;
1866     }
1867 
1868     // Calculate final jpeg buffer size for the given resolution.
1869     float scaleFactor =
1870             ((float)(width * height)) / (mMaxJpegResolution.width * mMaxJpegResolution.height);
1871     ssize_t jpegBufferSize =
1872             scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) + kMinJpegBufferSize;
1873     if (jpegBufferSize > maxJpegBufferSize) {
1874         jpegBufferSize = maxJpegBufferSize;
1875     }
1876 
1877     return jpegBufferSize;
1878 }
dump(int fd,const char **,uint32_t)1879 binder_status_t ExternalCameraDeviceSession::dump(int fd, const char** /*args*/,
1880                                                   uint32_t /*numArgs*/) {
1881     bool intfLocked = tryLock(mInterfaceLock);
1882     if (!intfLocked) {
1883         dprintf(fd, "!! ExternalCameraDeviceSession interface may be deadlocked !!\n");
1884     }
1885 
1886     if (isClosed()) {
1887         dprintf(fd, "External camera %s is closed\n", mCameraId.c_str());
1888         return STATUS_OK;
1889     }
1890 
1891     bool streaming = false;
1892     size_t v4L2BufferCount = 0;
1893     SupportedV4L2Format streamingFmt;
1894     {
1895         bool sessionLocked = tryLock(mLock);
1896         if (!sessionLocked) {
1897             dprintf(fd, "!! ExternalCameraDeviceSession mLock may be deadlocked !!\n");
1898         }
1899         streaming = mV4l2Streaming;
1900         streamingFmt = mV4l2StreamingFmt;
1901         v4L2BufferCount = mV4L2BufferCount;
1902 
1903         if (sessionLocked) {
1904             mLock.unlock();
1905         }
1906     }
1907 
1908     std::unordered_set<uint32_t> inflightFrames;
1909     {
1910         bool iffLocked = tryLock(mInflightFramesLock);
1911         if (!iffLocked) {
1912             dprintf(fd,
1913                     "!! ExternalCameraDeviceSession mInflightFramesLock may be deadlocked !!\n");
1914         }
1915         inflightFrames = mInflightFrames;
1916         if (iffLocked) {
1917             mInflightFramesLock.unlock();
1918         }
1919     }
1920 
1921     dprintf(fd, "External camera %s V4L2 FD %d, cropping type %s, %s\n", mCameraId.c_str(),
1922             mV4l2Fd.get(), (mCroppingType == VERTICAL) ? "vertical" : "horizontal",
1923             streaming ? "streaming" : "not streaming");
1924 
1925     if (streaming) {
1926         // TODO: dump fps later
1927         dprintf(fd, "Current V4L2 format %c%c%c%c %dx%d @ %ffps\n", streamingFmt.fourcc & 0xFF,
1928                 (streamingFmt.fourcc >> 8) & 0xFF, (streamingFmt.fourcc >> 16) & 0xFF,
1929                 (streamingFmt.fourcc >> 24) & 0xFF, streamingFmt.width, streamingFmt.height,
1930                 mV4l2StreamingFps);
1931 
1932         size_t numDequeuedV4l2Buffers = 0;
1933         {
1934             std::lock_guard<std::mutex> lk(mV4l2BufferLock);
1935             numDequeuedV4l2Buffers = mNumDequeuedV4l2Buffers;
1936         }
1937         dprintf(fd, "V4L2 buffer queue size %zu, dequeued %zu\n", v4L2BufferCount,
1938                 numDequeuedV4l2Buffers);
1939     }
1940 
1941     dprintf(fd, "In-flight frames (not sorted):");
1942     for (const auto& frameNumber : inflightFrames) {
1943         dprintf(fd, "%d, ", frameNumber);
1944     }
1945     dprintf(fd, "\n");
1946     mOutputThread->dump(fd);
1947     dprintf(fd, "\n");
1948 
1949     if (intfLocked) {
1950         mInterfaceLock.unlock();
1951     }
1952 
1953     return STATUS_OK;
1954 }
1955 
1956 // Start ExternalCameraDeviceSession::BufferRequestThread functions
BufferRequestThread(std::weak_ptr<OutputThreadInterface> parent,std::shared_ptr<ICameraDeviceCallback> callbacks)1957 ExternalCameraDeviceSession::BufferRequestThread::BufferRequestThread(
1958         std::weak_ptr<OutputThreadInterface> parent,
1959         std::shared_ptr<ICameraDeviceCallback> callbacks)
1960     : mParent(parent), mCallbacks(callbacks) {}
1961 
requestBufferStart(const std::vector<HalStreamBuffer> & bufReqs)1962 int ExternalCameraDeviceSession::BufferRequestThread::requestBufferStart(
1963         const std::vector<HalStreamBuffer>& bufReqs) {
1964     if (bufReqs.empty()) {
1965         ALOGE("%s: bufReqs is empty!", __FUNCTION__);
1966         return -1;
1967     }
1968 
1969     {
1970         std::lock_guard<std::mutex> lk(mLock);
1971         if (mRequestingBuffer) {
1972             ALOGE("%s: BufferRequestThread does not support more than one concurrent request!",
1973                   __FUNCTION__);
1974             return -1;
1975         }
1976 
1977         mBufferReqs = bufReqs;
1978         mRequestingBuffer = true;
1979     }
1980     mRequestCond.notify_one();
1981     return 0;
1982 }
1983 
waitForBufferRequestDone(std::vector<HalStreamBuffer> * outBufReqs)1984 int ExternalCameraDeviceSession::BufferRequestThread::waitForBufferRequestDone(
1985         std::vector<HalStreamBuffer>* outBufReqs) {
1986     std::unique_lock<std::mutex> lk(mLock);
1987     if (!mRequestingBuffer) {
1988         ALOGE("%s: no pending buffer request!", __FUNCTION__);
1989         return -1;
1990     }
1991 
1992     if (mPendingReturnBufferReqs.empty()) {
1993         std::chrono::milliseconds timeout = std::chrono::milliseconds(kReqProcTimeoutMs);
1994         auto st = mRequestDoneCond.wait_for(lk, timeout);
1995         if (st == std::cv_status::timeout) {
1996             mRequestingBuffer = false;
1997             ALOGE("%s: wait for buffer request finish timeout!", __FUNCTION__);
1998             return -1;
1999         }
2000 
2001         if (mPendingReturnBufferReqs.empty()) {
2002             mRequestingBuffer = false;
2003             ALOGE("%s: cameraservice did not return any buffers!", __FUNCTION__);
2004             return -1;
2005         }
2006     }
2007     mRequestingBuffer = false;
2008     *outBufReqs = std::move(mPendingReturnBufferReqs);
2009     mPendingReturnBufferReqs.clear();
2010     return 0;
2011 }
2012 
waitForNextRequest()2013 void ExternalCameraDeviceSession::BufferRequestThread::waitForNextRequest() {
2014     ATRACE_CALL();
2015     std::unique_lock<std::mutex> lk(mLock);
2016     int waitTimes = 0;
2017     while (mBufferReqs.empty()) {
2018         if (exitPending()) {
2019             return;
2020         }
2021         auto timeout = std::chrono::milliseconds(kReqWaitTimeoutMs);
2022         auto st = mRequestCond.wait_for(lk, timeout);
2023         if (st == std::cv_status::timeout) {
2024             waitTimes++;
2025             if (waitTimes == kReqWaitTimesWarn) {
2026                 // BufferRequestThread just wait forever for new buffer request
2027                 // But it will print some periodic warning indicating it's waiting
2028                 ALOGV("%s: still waiting for new buffer request", __FUNCTION__);
2029                 waitTimes = 0;
2030             }
2031         }
2032     }
2033 
2034     // Fill in BufferRequest
2035     mHalBufferReqs.resize(mBufferReqs.size());
2036     for (size_t i = 0; i < mHalBufferReqs.size(); i++) {
2037         mHalBufferReqs[i].streamId = mBufferReqs[i].streamId;
2038         mHalBufferReqs[i].numBuffersRequested = 1;
2039     }
2040 }
2041 
threadLoop()2042 bool ExternalCameraDeviceSession::BufferRequestThread::threadLoop() {
2043     waitForNextRequest();
2044     if (exitPending()) {
2045         return false;
2046     }
2047 
2048     ATRACE_BEGIN("AIDL requestStreamBuffers");
2049     BufferRequestStatus status;
2050     std::vector<StreamBufferRet> bufRets;
2051     ScopedAStatus ret = mCallbacks->requestStreamBuffers(mHalBufferReqs, &bufRets, &status);
2052     if (!ret.isOk()) {
2053         ALOGE("%s: Transaction error: %d:%d", __FUNCTION__, ret.getExceptionCode(),
2054               ret.getServiceSpecificError());
2055         mBufferReqs.clear();
2056         mRequestDoneCond.notify_one();
2057         return false;
2058     }
2059 
2060     std::unique_lock<std::mutex> lk(mLock);
2061     if (status == BufferRequestStatus::OK || status == BufferRequestStatus::FAILED_PARTIAL) {
2062         if (bufRets.size() != mHalBufferReqs.size()) {
2063             ALOGE("%s: expect %zu buffer requests returned, only got %zu", __FUNCTION__,
2064                   mHalBufferReqs.size(), bufRets.size());
2065             mBufferReqs.clear();
2066             lk.unlock();
2067             mRequestDoneCond.notify_one();
2068             return false;
2069         }
2070 
2071         auto parent = mParent.lock();
2072         if (parent == nullptr) {
2073             ALOGE("%s: session has been disconnected!", __FUNCTION__);
2074             mBufferReqs.clear();
2075             lk.unlock();
2076             mRequestDoneCond.notify_one();
2077             return false;
2078         }
2079 
2080         std::vector<int> importedFences;
2081         importedFences.resize(bufRets.size());
2082         bool hasError = false;
2083         for (size_t i = 0; i < bufRets.size(); i++) {
2084             int streamId = bufRets[i].streamId;
2085             switch (bufRets[i].val.getTag()) {
2086                 case StreamBuffersVal::Tag::error:
2087                     continue;
2088                 case StreamBuffersVal::Tag::buffers: {
2089                     const std::vector<StreamBuffer>& hBufs =
2090                             bufRets[i].val.get<StreamBuffersVal::Tag::buffers>();
2091                     if (hBufs.size() != 1) {
2092                         ALOGE("%s: expect 1 buffer returned, got %zu!", __FUNCTION__, hBufs.size());
2093                         hasError = true;
2094                         break;
2095                     }
2096                     const StreamBuffer& hBuf = hBufs[0];
2097 
2098                     mBufferReqs[i].bufferId = hBuf.bufferId;
2099                     // TODO: create a batch import API so we don't need to lock/unlock mCbsLock
2100                     // repeatedly?
2101                     lk.unlock();
2102                     native_handle_t* h = makeFromAidl(hBuf.buffer);
2103                     Status s = parent->importBuffer(streamId, hBuf.bufferId, h,
2104                                                     /*out*/ &mBufferReqs[i].bufPtr);
2105                     native_handle_delete(h);
2106                     lk.lock();
2107 
2108                     if (s != Status::OK) {
2109                         ALOGE("%s: stream %d import buffer failed!", __FUNCTION__, streamId);
2110                         cleanupInflightFences(importedFences, i - 1);
2111                         hasError = true;
2112                         break;
2113                     }
2114                     h = makeFromAidl(hBuf.acquireFence);
2115                     if (!sHandleImporter.importFence(h, mBufferReqs[i].acquireFence)) {
2116                         ALOGE("%s: stream %d import fence failed!", __FUNCTION__, streamId);
2117                         cleanupInflightFences(importedFences, i - 1);
2118                         native_handle_delete(h);
2119                         hasError = true;
2120                         break;
2121                     }
2122                     native_handle_delete(h);
2123                     importedFences[i] = mBufferReqs[i].acquireFence;
2124                 } break;
2125                 default:
2126                     ALOGE("%s: Unknown StreamBuffersVal!", __FUNCTION__);
2127                     hasError = true;
2128                     break;
2129             }
2130             if (hasError) {
2131                 mBufferReqs.clear();
2132                 lk.unlock();
2133                 mRequestDoneCond.notify_one();
2134                 return true;
2135             }
2136         }
2137     } else {
2138         ALOGE("%s: requestStreamBuffers call failed!", __FUNCTION__);
2139         mBufferReqs.clear();
2140         lk.unlock();
2141         mRequestDoneCond.notify_one();
2142         return true;
2143     }
2144 
2145     mPendingReturnBufferReqs = std::move(mBufferReqs);
2146     mBufferReqs.clear();
2147 
2148     lk.unlock();
2149     mRequestDoneCond.notify_one();
2150     return true;
2151 }
2152 
2153 // End ExternalCameraDeviceSession::BufferRequestThread functions
2154 
2155 // Start ExternalCameraDeviceSession::OutputThread functions
2156 
OutputThread(std::weak_ptr<OutputThreadInterface> parent,CroppingType ct,const common::V1_0::helper::CameraMetadata & chars,std::shared_ptr<BufferRequestThread> bufReqThread)2157 ExternalCameraDeviceSession::OutputThread::OutputThread(
2158         std::weak_ptr<OutputThreadInterface> parent, CroppingType ct,
2159         const common::V1_0::helper::CameraMetadata& chars,
2160         std::shared_ptr<BufferRequestThread> bufReqThread)
2161     : mParent(parent),
2162       mCroppingType(ct),
2163       mCameraCharacteristics(chars),
2164       mBufferRequestThread(bufReqThread) {}
2165 
~OutputThread()2166 ExternalCameraDeviceSession::OutputThread::~OutputThread() {}
2167 
allocateIntermediateBuffers(const Size & v4lSize,const Size & thumbSize,const std::vector<Stream> & streams,uint32_t blobBufferSize)2168 Status ExternalCameraDeviceSession::OutputThread::allocateIntermediateBuffers(
2169         const Size& v4lSize, const Size& thumbSize, const std::vector<Stream>& streams,
2170         uint32_t blobBufferSize) {
2171     std::lock_guard<std::mutex> lk(mBufferLock);
2172     if (!mScaledYu12Frames.empty()) {
2173         ALOGE("%s: intermediate buffer pool has %zu inflight buffers! (expect 0)", __FUNCTION__,
2174               mScaledYu12Frames.size());
2175         return Status::INTERNAL_ERROR;
2176     }
2177 
2178     // Allocating intermediate YU12 frame
2179     if (mYu12Frame == nullptr || mYu12Frame->mWidth != v4lSize.width ||
2180         mYu12Frame->mHeight != v4lSize.height) {
2181         mYu12Frame.reset();
2182         mYu12Frame = std::make_shared<AllocatedFrame>(v4lSize.width, v4lSize.height);
2183         int ret = mYu12Frame->allocate(&mYu12FrameLayout);
2184         if (ret != 0) {
2185             ALOGE("%s: allocating YU12 frame failed!", __FUNCTION__);
2186             return Status::INTERNAL_ERROR;
2187         }
2188     }
2189 
2190     // Allocating intermediate YU12 thumbnail frame
2191     if (mYu12ThumbFrame == nullptr || mYu12ThumbFrame->mWidth != thumbSize.width ||
2192         mYu12ThumbFrame->mHeight != thumbSize.height) {
2193         mYu12ThumbFrame.reset();
2194         mYu12ThumbFrame = std::make_shared<AllocatedFrame>(thumbSize.width, thumbSize.height);
2195         int ret = mYu12ThumbFrame->allocate(&mYu12ThumbFrameLayout);
2196         if (ret != 0) {
2197             ALOGE("%s: allocating YU12 thumb frame failed!", __FUNCTION__);
2198             return Status::INTERNAL_ERROR;
2199         }
2200     }
2201 
2202     // Allocating scaled buffers
2203     for (const auto& stream : streams) {
2204         Size sz = {stream.width, stream.height};
2205         if (sz == v4lSize) {
2206             continue;  // Don't need an intermediate buffer same size as v4lBuffer
2207         }
2208         if (mIntermediateBuffers.count(sz) == 0) {
2209             // Create new intermediate buffer
2210             std::shared_ptr<AllocatedFrame> buf =
2211                     std::make_shared<AllocatedFrame>(stream.width, stream.height);
2212             int ret = buf->allocate();
2213             if (ret != 0) {
2214                 ALOGE("%s: allocating intermediate YU12 frame %dx%d failed!", __FUNCTION__,
2215                       stream.width, stream.height);
2216                 return Status::INTERNAL_ERROR;
2217             }
2218             mIntermediateBuffers[sz] = buf;
2219         }
2220     }
2221 
2222     // Remove unconfigured buffers
2223     auto it = mIntermediateBuffers.begin();
2224     while (it != mIntermediateBuffers.end()) {
2225         bool configured = false;
2226         auto sz = it->first;
2227         for (const auto& stream : streams) {
2228             if (stream.width == sz.width && stream.height == sz.height) {
2229                 configured = true;
2230                 break;
2231             }
2232         }
2233         if (configured) {
2234             it++;
2235         } else {
2236             it = mIntermediateBuffers.erase(it);
2237         }
2238     }
2239 
2240     // Allocate mute test pattern frame
2241     mMuteTestPatternFrame.resize(mYu12Frame->mWidth * mYu12Frame->mHeight * 3);
2242 
2243     mBlobBufferSize = blobBufferSize;
2244     return Status::OK;
2245 }
2246 
submitRequest(const std::shared_ptr<HalRequest> & req)2247 Status ExternalCameraDeviceSession::OutputThread::submitRequest(
2248         const std::shared_ptr<HalRequest>& req) {
2249     std::unique_lock<std::mutex> lk(mRequestListLock);
2250     mRequestList.push_back(req);
2251     lk.unlock();
2252     mRequestCond.notify_one();
2253     return Status::OK;
2254 }
2255 
flush()2256 void ExternalCameraDeviceSession::OutputThread::flush() {
2257     ATRACE_CALL();
2258     auto parent = mParent.lock();
2259     if (parent == nullptr) {
2260         ALOGE("%s: session has been disconnected!", __FUNCTION__);
2261         return;
2262     }
2263 
2264     std::unique_lock<std::mutex> lk(mRequestListLock);
2265     std::list<std::shared_ptr<HalRequest>> reqs = std::move(mRequestList);
2266     mRequestList.clear();
2267     if (mProcessingRequest) {
2268         auto timeout = std::chrono::seconds(kFlushWaitTimeoutSec);
2269         auto st = mRequestDoneCond.wait_for(lk, timeout);
2270         if (st == std::cv_status::timeout) {
2271             ALOGE("%s: wait for inflight request finish timeout!", __FUNCTION__);
2272         }
2273     }
2274 
2275     ALOGV("%s: flushing inflight requests", __FUNCTION__);
2276     lk.unlock();
2277     for (const auto& req : reqs) {
2278         parent->processCaptureRequestError(req);
2279     }
2280 }
2281 
dump(int fd)2282 void ExternalCameraDeviceSession::OutputThread::dump(int fd) {
2283     std::lock_guard<std::mutex> lk(mRequestListLock);
2284     if (mProcessingRequest) {
2285         dprintf(fd, "OutputThread processing frame %d\n", mProcessingFrameNumber);
2286     } else {
2287         dprintf(fd, "OutputThread not processing any frames\n");
2288     }
2289     dprintf(fd, "OutputThread request list contains frame: ");
2290     for (const auto& req : mRequestList) {
2291         dprintf(fd, "%d, ", req->frameNumber);
2292     }
2293     dprintf(fd, "\n");
2294 }
2295 
setExifMakeModel(const std::string & make,const std::string & model)2296 void ExternalCameraDeviceSession::OutputThread::setExifMakeModel(const std::string& make,
2297                                                                  const std::string& model) {
2298     mExifMake = make;
2299     mExifModel = model;
2300 }
2301 
2302 std::list<std::shared_ptr<HalRequest>>
switchToOffline()2303 ExternalCameraDeviceSession::OutputThread::switchToOffline() {
2304     ATRACE_CALL();
2305     auto parent = mParent.lock();
2306     if (parent == nullptr) {
2307         ALOGE("%s: session has been disconnected!", __FUNCTION__);
2308         return {};
2309     }
2310 
2311     std::unique_lock<std::mutex> lk(mRequestListLock);
2312     std::list<std::shared_ptr<HalRequest>> reqs = std::move(mRequestList);
2313     mRequestList.clear();
2314     if (mProcessingRequest) {
2315         auto timeout = std::chrono::seconds(kFlushWaitTimeoutSec);
2316         auto st = mRequestDoneCond.wait_for(lk, timeout);
2317         if (st == std::cv_status::timeout) {
2318             ALOGE("%s: wait for inflight request finish timeout!", __FUNCTION__);
2319         }
2320     }
2321     lk.unlock();
2322     clearIntermediateBuffers();
2323     ALOGV("%s: returning %zu request for offline processing", __FUNCTION__, reqs.size());
2324     return reqs;
2325 }
2326 
requestBufferStart(const std::vector<HalStreamBuffer> & bufs)2327 int ExternalCameraDeviceSession::OutputThread::requestBufferStart(
2328         const std::vector<HalStreamBuffer>& bufs) {
2329     if (mBufferRequestThread == nullptr) {
2330         return 0;
2331     }
2332     return mBufferRequestThread->requestBufferStart(bufs);
2333 }
2334 
waitForBufferRequestDone(std::vector<HalStreamBuffer> * outBufs)2335 int ExternalCameraDeviceSession::OutputThread::waitForBufferRequestDone(
2336         std::vector<HalStreamBuffer>* outBufs) {
2337     if (mBufferRequestThread == nullptr) {
2338         return 0;
2339     }
2340     return mBufferRequestThread->waitForBufferRequestDone(outBufs);
2341 }
2342 
waitForNextRequest(std::shared_ptr<HalRequest> * out)2343 void ExternalCameraDeviceSession::OutputThread::waitForNextRequest(
2344         std::shared_ptr<HalRequest>* out) {
2345     ATRACE_CALL();
2346     if (out == nullptr) {
2347         ALOGE("%s: out is null", __FUNCTION__);
2348         return;
2349     }
2350 
2351     std::unique_lock<std::mutex> lk(mRequestListLock);
2352     int waitTimes = 0;
2353     while (mRequestList.empty()) {
2354         if (exitPending()) {
2355             return;
2356         }
2357         auto timeout = std::chrono::milliseconds(kReqWaitTimeoutMs);
2358         auto st = mRequestCond.wait_for(lk, timeout);
2359         if (st == std::cv_status::timeout) {
2360             waitTimes++;
2361             if (waitTimes == kReqWaitTimesMax) {
2362                 // no new request, return
2363                 return;
2364             }
2365         }
2366     }
2367     *out = mRequestList.front();
2368     mRequestList.pop_front();
2369     mProcessingRequest = true;
2370     mProcessingFrameNumber = (*out)->frameNumber;
2371 }
2372 
signalRequestDone()2373 void ExternalCameraDeviceSession::OutputThread::signalRequestDone() {
2374     std::unique_lock<std::mutex> lk(mRequestListLock);
2375     mProcessingRequest = false;
2376     mProcessingFrameNumber = 0;
2377     lk.unlock();
2378     mRequestDoneCond.notify_one();
2379 }
2380 
cropAndScaleLocked(std::shared_ptr<AllocatedFrame> & in,const Size & outSz,YCbCrLayout * out)2381 int ExternalCameraDeviceSession::OutputThread::cropAndScaleLocked(
2382         std::shared_ptr<AllocatedFrame>& in, const Size& outSz, YCbCrLayout* out) {
2383     Size inSz = {in->mWidth, in->mHeight};
2384 
2385     int ret;
2386     if (inSz == outSz) {
2387         ret = in->getLayout(out);
2388         if (ret != 0) {
2389             ALOGE("%s: failed to get input image layout", __FUNCTION__);
2390             return ret;
2391         }
2392         return ret;
2393     }
2394 
2395     // Cropping to output aspect ratio
2396     IMapper::Rect inputCrop;
2397     ret = getCropRect(mCroppingType, inSz, outSz, &inputCrop);
2398     if (ret != 0) {
2399         ALOGE("%s: failed to compute crop rect for output size %dx%d", __FUNCTION__, outSz.width,
2400               outSz.height);
2401         return ret;
2402     }
2403 
2404     YCbCrLayout croppedLayout;
2405     ret = in->getCroppedLayout(inputCrop, &croppedLayout);
2406     if (ret != 0) {
2407         ALOGE("%s: failed to crop input image %dx%d to output size %dx%d", __FUNCTION__, inSz.width,
2408               inSz.height, outSz.width, outSz.height);
2409         return ret;
2410     }
2411 
2412     if ((mCroppingType == VERTICAL && inSz.width == outSz.width) ||
2413         (mCroppingType == HORIZONTAL && inSz.height == outSz.height)) {
2414         // No scale is needed
2415         *out = croppedLayout;
2416         return 0;
2417     }
2418 
2419     auto it = mScaledYu12Frames.find(outSz);
2420     std::shared_ptr<AllocatedFrame> scaledYu12Buf;
2421     if (it != mScaledYu12Frames.end()) {
2422         scaledYu12Buf = it->second;
2423     } else {
2424         it = mIntermediateBuffers.find(outSz);
2425         if (it == mIntermediateBuffers.end()) {
2426             ALOGE("%s: failed to find intermediate buffer size %dx%d", __FUNCTION__, outSz.width,
2427                   outSz.height);
2428             return -1;
2429         }
2430         scaledYu12Buf = it->second;
2431     }
2432     // Scale
2433     YCbCrLayout outLayout;
2434     ret = scaledYu12Buf->getLayout(&outLayout);
2435     if (ret != 0) {
2436         ALOGE("%s: failed to get output buffer layout", __FUNCTION__);
2437         return ret;
2438     }
2439 
2440     ret = libyuv::I420Scale(
2441             static_cast<uint8_t*>(croppedLayout.y), croppedLayout.yStride,
2442             static_cast<uint8_t*>(croppedLayout.cb), croppedLayout.cStride,
2443             static_cast<uint8_t*>(croppedLayout.cr), croppedLayout.cStride, inputCrop.width,
2444             inputCrop.height, static_cast<uint8_t*>(outLayout.y), outLayout.yStride,
2445             static_cast<uint8_t*>(outLayout.cb), outLayout.cStride,
2446             static_cast<uint8_t*>(outLayout.cr), outLayout.cStride, outSz.width, outSz.height,
2447             // TODO: b/72261744 see if we can use better filter without losing too much perf
2448             libyuv::FilterMode::kFilterNone);
2449 
2450     if (ret != 0) {
2451         ALOGE("%s: failed to scale buffer from %dx%d to %dx%d. Ret %d", __FUNCTION__,
2452               inputCrop.width, inputCrop.height, outSz.width, outSz.height, ret);
2453         return ret;
2454     }
2455 
2456     *out = outLayout;
2457     mScaledYu12Frames.insert({outSz, scaledYu12Buf});
2458     return 0;
2459 }
2460 
cropAndScaleThumbLocked(std::shared_ptr<AllocatedFrame> & in,const Size & outSz,YCbCrLayout * out)2461 int ExternalCameraDeviceSession::OutputThread::cropAndScaleThumbLocked(
2462         std::shared_ptr<AllocatedFrame>& in, const Size& outSz, YCbCrLayout* out) {
2463     Size inSz{in->mWidth, in->mHeight};
2464 
2465     if ((outSz.width * outSz.height) > (mYu12ThumbFrame->mWidth * mYu12ThumbFrame->mHeight)) {
2466         ALOGE("%s: Requested thumbnail size too big (%d,%d) > (%d,%d)", __FUNCTION__, outSz.width,
2467               outSz.height, mYu12ThumbFrame->mWidth, mYu12ThumbFrame->mHeight);
2468         return -1;
2469     }
2470 
2471     int ret;
2472 
2473     /* This will crop-and-zoom the input YUV frame to the thumbnail size
2474      * Based on the following logic:
2475      *  1) Square pixels come in, square pixels come out, therefore single
2476      *  scale factor is computed to either make input bigger or smaller
2477      *  depending on if we are upscaling or downscaling
2478      *  2) That single scale factor would either make height too tall or width
2479      *  too wide so we need to crop the input either horizontally or vertically
2480      *  but not both
2481      */
2482 
2483     /* Convert the input and output dimensions into floats for ease of math */
2484     float fWin = static_cast<float>(inSz.width);
2485     float fHin = static_cast<float>(inSz.height);
2486     float fWout = static_cast<float>(outSz.width);
2487     float fHout = static_cast<float>(outSz.height);
2488 
2489     /* Compute the one scale factor from (1) above, it will be the smaller of
2490      * the two possibilities. */
2491     float scaleFactor = std::min(fHin / fHout, fWin / fWout);
2492 
2493     /* Since we are crop-and-zooming (as opposed to letter/pillar boxing) we can
2494      * simply multiply the output by our scaleFactor to get the cropped input
2495      * size. Note that at least one of {fWcrop, fHcrop} is going to wind up
2496      * being {fWin, fHin} respectively because fHout or fWout cancels out the
2497      * scaleFactor calculation above.
2498      *
2499      * Specifically:
2500      *  if ( fHin / fHout ) < ( fWin / fWout ) we crop the sides off
2501      * input, in which case
2502      *    scaleFactor = fHin / fHout
2503      *    fWcrop = fHin / fHout * fWout
2504      *    fHcrop = fHin
2505      *
2506      * Note that fWcrop <= fWin ( because ( fHin / fHout ) * fWout < fWin, which
2507      * is just the inequality above with both sides multiplied by fWout
2508      *
2509      * on the other hand if ( fWin / fWout ) < ( fHin / fHout) we crop the top
2510      * and the bottom off of input, and
2511      *    scaleFactor = fWin / fWout
2512      *    fWcrop = fWin
2513      *    fHCrop = fWin / fWout * fHout
2514      */
2515     float fWcrop = scaleFactor * fWout;
2516     float fHcrop = scaleFactor * fHout;
2517 
2518     /* Convert to integer and truncate to an even number */
2519     Size cropSz = {.width = 2 * static_cast<int32_t>(fWcrop / 2.0f),
2520                    .height = 2 * static_cast<int32_t>(fHcrop / 2.0f)};
2521 
2522     /* Convert to a centered rectange with even top/left */
2523     IMapper::Rect inputCrop{.left = 2 * static_cast<int32_t>((inSz.width - cropSz.width) / 4),
2524                             .top = 2 * static_cast<int32_t>((inSz.height - cropSz.height) / 4),
2525                             .width = static_cast<int32_t>(cropSz.width),
2526                             .height = static_cast<int32_t>(cropSz.height)};
2527 
2528     if ((inputCrop.top < 0) || (inputCrop.top >= static_cast<int32_t>(inSz.height)) ||
2529         (inputCrop.left < 0) || (inputCrop.left >= static_cast<int32_t>(inSz.width)) ||
2530         (inputCrop.width <= 0) ||
2531         (inputCrop.width + inputCrop.left > static_cast<int32_t>(inSz.width)) ||
2532         (inputCrop.height <= 0) ||
2533         (inputCrop.height + inputCrop.top > static_cast<int32_t>(inSz.height))) {
2534         ALOGE("%s: came up with really wrong crop rectangle", __FUNCTION__);
2535         ALOGE("%s: input layout %dx%d to for output size %dx%d", __FUNCTION__, inSz.width,
2536               inSz.height, outSz.width, outSz.height);
2537         ALOGE("%s: computed input crop +%d,+%d %dx%d", __FUNCTION__, inputCrop.left, inputCrop.top,
2538               inputCrop.width, inputCrop.height);
2539         return -1;
2540     }
2541 
2542     YCbCrLayout inputLayout;
2543     ret = in->getCroppedLayout(inputCrop, &inputLayout);
2544     if (ret != 0) {
2545         ALOGE("%s: failed to crop input layout %dx%d to for output size %dx%d", __FUNCTION__,
2546               inSz.width, inSz.height, outSz.width, outSz.height);
2547         ALOGE("%s: computed input crop +%d,+%d %dx%d", __FUNCTION__, inputCrop.left, inputCrop.top,
2548               inputCrop.width, inputCrop.height);
2549         return ret;
2550     }
2551     ALOGV("%s: crop input layout %dx%d to for output size %dx%d", __FUNCTION__, inSz.width,
2552           inSz.height, outSz.width, outSz.height);
2553     ALOGV("%s: computed input crop +%d,+%d %dx%d", __FUNCTION__, inputCrop.left, inputCrop.top,
2554           inputCrop.width, inputCrop.height);
2555 
2556     // Scale
2557     YCbCrLayout outFullLayout;
2558 
2559     ret = mYu12ThumbFrame->getLayout(&outFullLayout);
2560     if (ret != 0) {
2561         ALOGE("%s: failed to get output buffer layout", __FUNCTION__);
2562         return ret;
2563     }
2564 
2565     ret = libyuv::I420Scale(static_cast<uint8_t*>(inputLayout.y), inputLayout.yStride,
2566                             static_cast<uint8_t*>(inputLayout.cb), inputLayout.cStride,
2567                             static_cast<uint8_t*>(inputLayout.cr), inputLayout.cStride,
2568                             inputCrop.width, inputCrop.height,
2569                             static_cast<uint8_t*>(outFullLayout.y), outFullLayout.yStride,
2570                             static_cast<uint8_t*>(outFullLayout.cb), outFullLayout.cStride,
2571                             static_cast<uint8_t*>(outFullLayout.cr), outFullLayout.cStride,
2572                             outSz.width, outSz.height, libyuv::FilterMode::kFilterNone);
2573 
2574     if (ret != 0) {
2575         ALOGE("%s: failed to scale buffer from %dx%d to %dx%d. Ret %d", __FUNCTION__,
2576               inputCrop.width, inputCrop.height, outSz.width, outSz.height, ret);
2577         return ret;
2578     }
2579 
2580     *out = outFullLayout;
2581     return 0;
2582 }
2583 
createJpegLocked(HalStreamBuffer & halBuf,const common::V1_0::helper::CameraMetadata & setting)2584 int ExternalCameraDeviceSession::OutputThread::createJpegLocked(
2585         HalStreamBuffer& halBuf, const common::V1_0::helper::CameraMetadata& setting) {
2586     ATRACE_CALL();
2587     int ret;
2588     auto lfail = [&](auto... args) {
2589         ALOGE(args...);
2590 
2591         return 1;
2592     };
2593     auto parent = mParent.lock();
2594     if (parent == nullptr) {
2595         ALOGE("%s: session has been disconnected!", __FUNCTION__);
2596         return 1;
2597     }
2598 
2599     ALOGV("%s: HAL buffer sid: %d bid: %" PRIu64 " w: %u h: %u", __FUNCTION__, halBuf.streamId,
2600           static_cast<uint64_t>(halBuf.bufferId), halBuf.width, halBuf.height);
2601     ALOGV("%s: HAL buffer fmt: %x usage: %" PRIx64 " ptr: %p", __FUNCTION__, halBuf.format,
2602           static_cast<uint64_t>(halBuf.usage), halBuf.bufPtr);
2603     ALOGV("%s: YV12 buffer %d x %d", __FUNCTION__, mYu12Frame->mWidth, mYu12Frame->mHeight);
2604 
2605     int jpegQuality, thumbQuality;
2606     Size thumbSize;
2607     bool outputThumbnail = true;
2608 
2609     if (setting.exists(ANDROID_JPEG_QUALITY)) {
2610         camera_metadata_ro_entry entry = setting.find(ANDROID_JPEG_QUALITY);
2611         jpegQuality = entry.data.u8[0];
2612     } else {
2613         return lfail("%s: ANDROID_JPEG_QUALITY not set", __FUNCTION__);
2614     }
2615 
2616     if (setting.exists(ANDROID_JPEG_THUMBNAIL_QUALITY)) {
2617         camera_metadata_ro_entry entry = setting.find(ANDROID_JPEG_THUMBNAIL_QUALITY);
2618         thumbQuality = entry.data.u8[0];
2619     } else {
2620         return lfail("%s: ANDROID_JPEG_THUMBNAIL_QUALITY not set", __FUNCTION__);
2621     }
2622 
2623     if (setting.exists(ANDROID_JPEG_THUMBNAIL_SIZE)) {
2624         camera_metadata_ro_entry entry = setting.find(ANDROID_JPEG_THUMBNAIL_SIZE);
2625         thumbSize = Size{.width = entry.data.i32[0], .height = entry.data.i32[1]};
2626         if (thumbSize.width == 0 && thumbSize.height == 0) {
2627             outputThumbnail = false;
2628         }
2629     } else {
2630         return lfail("%s: ANDROID_JPEG_THUMBNAIL_SIZE not set", __FUNCTION__);
2631     }
2632 
2633     /* Cropped and scaled YU12 buffer for main and thumbnail */
2634     YCbCrLayout yu12Main;
2635     Size jpegSize{halBuf.width, halBuf.height};
2636 
2637     /* Compute temporary buffer sizes accounting for the following:
2638      * thumbnail can't exceed APP1 size of 64K
2639      * main image needs to hold APP1, headers, and at most a poorly
2640      * compressed image */
2641     const ssize_t maxThumbCodeSize = 64 * 1024;
2642     const ssize_t maxJpegCodeSize =
2643             mBlobBufferSize == 0 ? parent->getJpegBufferSize(jpegSize.width, jpegSize.height)
2644                                  : mBlobBufferSize;
2645 
2646     /* Check that getJpegBufferSize did not return an error */
2647     if (maxJpegCodeSize < 0) {
2648         return lfail("%s: getJpegBufferSize returned %zd", __FUNCTION__, maxJpegCodeSize);
2649     }
2650 
2651     /* Hold actual thumbnail and main image code sizes */
2652     size_t thumbCodeSize = 0, jpegCodeSize = 0;
2653     /* Temporary thumbnail code buffer */
2654     std::vector<uint8_t> thumbCode(outputThumbnail ? maxThumbCodeSize : 0);
2655 
2656     YCbCrLayout yu12Thumb;
2657     if (outputThumbnail) {
2658         ret = cropAndScaleThumbLocked(mYu12Frame, thumbSize, &yu12Thumb);
2659 
2660         if (ret != 0) {
2661             return lfail("%s: crop and scale thumbnail failed!", __FUNCTION__);
2662         }
2663     }
2664 
2665     /* Scale and crop main jpeg */
2666     ret = cropAndScaleLocked(mYu12Frame, jpegSize, &yu12Main);
2667 
2668     if (ret != 0) {
2669         return lfail("%s: crop and scale main failed!", __FUNCTION__);
2670     }
2671 
2672     /* Encode the thumbnail image */
2673     if (outputThumbnail) {
2674         ret = encodeJpegYU12(thumbSize, yu12Thumb, thumbQuality, 0, 0, &thumbCode[0],
2675                              maxThumbCodeSize, thumbCodeSize);
2676 
2677         if (ret != 0) {
2678             return lfail("%s: thumbnail encodeJpegYU12 failed with %d", __FUNCTION__, ret);
2679         }
2680     }
2681 
2682     /* Combine camera characteristics with request settings to form EXIF
2683      * metadata */
2684     common::V1_0::helper::CameraMetadata meta(mCameraCharacteristics);
2685     meta.append(setting);
2686 
2687     /* Generate EXIF object */
2688     std::unique_ptr<ExifUtils> utils(ExifUtils::create());
2689     /* Make sure it's initialized */
2690     utils->initialize();
2691 
2692     utils->setFromMetadata(meta, jpegSize.width, jpegSize.height);
2693     utils->setMake(mExifMake);
2694     utils->setModel(mExifModel);
2695 
2696     ret = utils->generateApp1(outputThumbnail ? &thumbCode[0] : nullptr, thumbCodeSize);
2697 
2698     if (!ret) {
2699         return lfail("%s: generating APP1 failed", __FUNCTION__);
2700     }
2701 
2702     /* Get internal buffer */
2703     size_t exifDataSize = utils->getApp1Length();
2704     const uint8_t* exifData = utils->getApp1Buffer();
2705 
2706     /* Lock the HAL jpeg code buffer */
2707     void* bufPtr = sHandleImporter.lock(*(halBuf.bufPtr), static_cast<uint64_t>(halBuf.usage),
2708                                         maxJpegCodeSize);
2709 
2710     if (!bufPtr) {
2711         return lfail("%s: could not lock %zu bytes", __FUNCTION__, maxJpegCodeSize);
2712     }
2713 
2714     /* Encode the main jpeg image */
2715     ret = encodeJpegYU12(jpegSize, yu12Main, jpegQuality, exifData, exifDataSize, bufPtr,
2716                          maxJpegCodeSize, jpegCodeSize);
2717 
2718     /* TODO: Not sure this belongs here, maybe better to pass jpegCodeSize out
2719      * and do this when returning buffer to parent */
2720     CameraBlob blob{CameraBlobId::JPEG, static_cast<int32_t>(jpegCodeSize)};
2721     void* blobDst = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(bufPtr) + maxJpegCodeSize -
2722                                             sizeof(CameraBlob));
2723     memcpy(blobDst, &blob, sizeof(CameraBlob));
2724 
2725     /* Unlock the HAL jpeg code buffer */
2726     int relFence = sHandleImporter.unlock(*(halBuf.bufPtr));
2727     if (relFence >= 0) {
2728         halBuf.acquireFence = relFence;
2729     }
2730 
2731     /* Check if our JPEG actually succeeded */
2732     if (ret != 0) {
2733         return lfail("%s: encodeJpegYU12 failed with %d", __FUNCTION__, ret);
2734     }
2735 
2736     ALOGV("%s: encoded JPEG (ret:%d) with Q:%d max size: %zu", __FUNCTION__, ret, jpegQuality,
2737           maxJpegCodeSize);
2738 
2739     return 0;
2740 }
2741 
clearIntermediateBuffers()2742 void ExternalCameraDeviceSession::OutputThread::clearIntermediateBuffers() {
2743     std::lock_guard<std::mutex> lk(mBufferLock);
2744     mYu12Frame.reset();
2745     mYu12ThumbFrame.reset();
2746     mIntermediateBuffers.clear();
2747     mMuteTestPatternFrame.clear();
2748     mBlobBufferSize = 0;
2749 }
2750 
threadLoop()2751 bool ExternalCameraDeviceSession::OutputThread::threadLoop() {
2752     std::shared_ptr<HalRequest> req;
2753     auto parent = mParent.lock();
2754     if (parent == nullptr) {
2755         ALOGE("%s: session has been disconnected!", __FUNCTION__);
2756         return false;
2757     }
2758 
2759     // TODO: maybe we need to setup a sensor thread to dq/enq v4l frames
2760     //       regularly to prevent v4l buffer queue filled with stale buffers
2761     //       when app doesn't program a preview request
2762     waitForNextRequest(&req);
2763     if (req == nullptr) {
2764         // No new request, wait again
2765         return true;
2766     }
2767 
2768     auto onDeviceError = [&](auto... args) {
2769         ALOGE(args...);
2770         parent->notifyError(req->frameNumber, /*stream*/ -1, ErrorCode::ERROR_DEVICE);
2771         signalRequestDone();
2772         return false;
2773     };
2774 
2775     if (req->frameIn->mFourcc != V4L2_PIX_FMT_MJPEG && req->frameIn->mFourcc != V4L2_PIX_FMT_Z16) {
2776         return onDeviceError("%s: do not support V4L2 format %c%c%c%c", __FUNCTION__,
2777                              req->frameIn->mFourcc & 0xFF, (req->frameIn->mFourcc >> 8) & 0xFF,
2778                              (req->frameIn->mFourcc >> 16) & 0xFF,
2779                              (req->frameIn->mFourcc >> 24) & 0xFF);
2780     }
2781 
2782     int res = requestBufferStart(req->buffers);
2783     if (res != 0) {
2784         ALOGE("%s: send BufferRequest failed! res %d", __FUNCTION__, res);
2785         return onDeviceError("%s: failed to send buffer request!", __FUNCTION__);
2786     }
2787 
2788     std::unique_lock<std::mutex> lk(mBufferLock);
2789     // Convert input V4L2 frame to YU12 of the same size
2790     // TODO: see if we can save some computation by converting to YV12 here
2791     uint8_t* inData;
2792     size_t inDataSize;
2793     if (req->frameIn->getData(&inData, &inDataSize) != 0) {
2794         lk.unlock();
2795         return onDeviceError("%s: V4L2 buffer map failed", __FUNCTION__);
2796     }
2797 
2798     // Process camera mute state
2799     auto testPatternMode = req->setting.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2800     if (testPatternMode.count == 1) {
2801         if (mCameraMuted != (testPatternMode.data.u8[0] != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF)) {
2802             mCameraMuted = !mCameraMuted;
2803             // Get solid color for test pattern, if any was set
2804             if (testPatternMode.data.u8[0] == ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
2805                 auto entry = req->setting.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2806                 if (entry.count == 4) {
2807                     // Update the mute frame if the pattern color has changed
2808                     if (memcmp(entry.data.i32, mTestPatternData, sizeof(mTestPatternData)) != 0) {
2809                         memcpy(mTestPatternData, entry.data.i32, sizeof(mTestPatternData));
2810                         // Fill the mute frame with the solid color, use only 8 MSB of RGGB as RGB
2811                         for (int i = 0; i < mMuteTestPatternFrame.size(); i += 3) {
2812                             mMuteTestPatternFrame[i] = entry.data.i32[0] >> 24;
2813                             mMuteTestPatternFrame[i + 1] = entry.data.i32[1] >> 24;
2814                             mMuteTestPatternFrame[i + 2] = entry.data.i32[3] >> 24;
2815                         }
2816                     }
2817                 }
2818             }
2819         }
2820     }
2821 
2822     // TODO: in some special case maybe we can decode jpg directly to gralloc output?
2823     if (req->frameIn->mFourcc == V4L2_PIX_FMT_MJPEG) {
2824         ATRACE_BEGIN("MJPGtoI420");
2825         res = 0;
2826         if (mCameraMuted) {
2827             res = libyuv::ConvertToI420(
2828                     mMuteTestPatternFrame.data(), mMuteTestPatternFrame.size(),
2829                     static_cast<uint8_t*>(mYu12FrameLayout.y), mYu12FrameLayout.yStride,
2830                     static_cast<uint8_t*>(mYu12FrameLayout.cb), mYu12FrameLayout.cStride,
2831                     static_cast<uint8_t*>(mYu12FrameLayout.cr), mYu12FrameLayout.cStride, 0, 0,
2832                     mYu12Frame->mWidth, mYu12Frame->mHeight, mYu12Frame->mWidth,
2833                     mYu12Frame->mHeight, libyuv::kRotate0, libyuv::FOURCC_RAW);
2834         } else {
2835             res = libyuv::MJPGToI420(
2836                     inData, inDataSize, static_cast<uint8_t*>(mYu12FrameLayout.y),
2837                     mYu12FrameLayout.yStride, static_cast<uint8_t*>(mYu12FrameLayout.cb),
2838                     mYu12FrameLayout.cStride, static_cast<uint8_t*>(mYu12FrameLayout.cr),
2839                     mYu12FrameLayout.cStride, mYu12Frame->mWidth, mYu12Frame->mHeight,
2840                     mYu12Frame->mWidth, mYu12Frame->mHeight);
2841         }
2842         ATRACE_END();
2843 
2844         if (res != 0) {
2845             // For some webcam, the first few V4L2 frames might be malformed...
2846             ALOGE("%s: Convert V4L2 frame to YU12 failed! res %d", __FUNCTION__, res);
2847 
2848             ATRACE_BEGIN("Wait for BufferRequest done");
2849             res = waitForBufferRequestDone(&req->buffers);
2850             ATRACE_END();
2851 
2852             lk.unlock();
2853             Status st = parent->processCaptureRequestError(req);
2854             if (st != Status::OK) {
2855                 return onDeviceError("%s: failed to process capture request error!", __FUNCTION__);
2856             }
2857             signalRequestDone();
2858             return true;
2859         }
2860     }
2861 
2862     ATRACE_BEGIN("Wait for BufferRequest done");
2863     res = waitForBufferRequestDone(&req->buffers);
2864     ATRACE_END();
2865 
2866     if (res != 0) {
2867         // HAL buffer management buffer request can fail
2868         ALOGE("%s: wait for BufferRequest done failed! res %d", __FUNCTION__, res);
2869         lk.unlock();
2870         Status st = parent->processCaptureRequestError(req);
2871         if (st != Status::OK) {
2872             return onDeviceError("%s: failed to process capture request error!", __FUNCTION__);
2873         }
2874         signalRequestDone();
2875         return true;
2876     }
2877 
2878     ALOGV("%s processing new request", __FUNCTION__);
2879     const int kSyncWaitTimeoutMs = 500;
2880     for (auto& halBuf : req->buffers) {
2881         if (*(halBuf.bufPtr) == nullptr) {
2882             ALOGW("%s: buffer for stream %d missing", __FUNCTION__, halBuf.streamId);
2883             halBuf.fenceTimeout = true;
2884         } else if (halBuf.acquireFence >= 0) {
2885             int ret = sync_wait(halBuf.acquireFence, kSyncWaitTimeoutMs);
2886             if (ret) {
2887                 halBuf.fenceTimeout = true;
2888             } else {
2889                 ::close(halBuf.acquireFence);
2890                 halBuf.acquireFence = -1;
2891             }
2892         }
2893 
2894         if (halBuf.fenceTimeout) {
2895             continue;
2896         }
2897 
2898         // Gralloc lockYCbCr the buffer
2899         switch (halBuf.format) {
2900             case PixelFormat::BLOB: {
2901                 int ret = createJpegLocked(halBuf, req->setting);
2902 
2903                 if (ret != 0) {
2904                     lk.unlock();
2905                     return onDeviceError("%s: createJpegLocked failed with %d", __FUNCTION__, ret);
2906                 }
2907             } break;
2908             case PixelFormat::Y16: {
2909                 void* outLayout = sHandleImporter.lock(
2910                         *(halBuf.bufPtr), static_cast<uint64_t>(halBuf.usage), inDataSize);
2911 
2912                 std::memcpy(outLayout, inData, inDataSize);
2913 
2914                 int relFence = sHandleImporter.unlock(*(halBuf.bufPtr));
2915                 if (relFence >= 0) {
2916                     halBuf.acquireFence = relFence;
2917                 }
2918             } break;
2919             case PixelFormat::YCBCR_420_888:
2920             case PixelFormat::YV12: {
2921                 android::Rect outRect{0, 0, static_cast<int32_t>(halBuf.width),
2922                                       static_cast<int32_t>(halBuf.height)};
2923                 android_ycbcr result = sHandleImporter.lockYCbCr(
2924                         *(halBuf.bufPtr), static_cast<uint64_t>(halBuf.usage), outRect);
2925                 ALOGV("%s: outLayout y %p cb %p cr %p y_str %zu c_str %zu c_step %zu", __FUNCTION__,
2926                       result.y, result.cb, result.cr, result.ystride, result.cstride,
2927                       result.chroma_step);
2928                 if (result.ystride > UINT32_MAX || result.cstride > UINT32_MAX ||
2929                     result.chroma_step > UINT32_MAX) {
2930                     return onDeviceError("%s: lockYCbCr failed. Unexpected values!", __FUNCTION__);
2931                 }
2932                 YCbCrLayout outLayout = {.y = result.y,
2933                                          .cb = result.cb,
2934                                          .cr = result.cr,
2935                                          .yStride = static_cast<uint32_t>(result.ystride),
2936                                          .cStride = static_cast<uint32_t>(result.cstride),
2937                                          .chromaStep = static_cast<uint32_t>(result.chroma_step)};
2938 
2939                 // Convert to output buffer size/format
2940                 uint32_t outputFourcc = getFourCcFromLayout(outLayout);
2941                 ALOGV("%s: converting to format %c%c%c%c", __FUNCTION__, outputFourcc & 0xFF,
2942                       (outputFourcc >> 8) & 0xFF, (outputFourcc >> 16) & 0xFF,
2943                       (outputFourcc >> 24) & 0xFF);
2944 
2945                 YCbCrLayout cropAndScaled;
2946                 ATRACE_BEGIN("cropAndScaleLocked");
2947                 int ret = cropAndScaleLocked(mYu12Frame, Size{halBuf.width, halBuf.height},
2948                                              &cropAndScaled);
2949                 ATRACE_END();
2950                 if (ret != 0) {
2951                     lk.unlock();
2952                     return onDeviceError("%s: crop and scale failed!", __FUNCTION__);
2953                 }
2954 
2955                 Size sz{halBuf.width, halBuf.height};
2956                 ATRACE_BEGIN("formatConvert");
2957                 ret = formatConvert(cropAndScaled, outLayout, sz, outputFourcc);
2958                 ATRACE_END();
2959                 if (ret != 0) {
2960                     lk.unlock();
2961                     return onDeviceError("%s: format conversion failed!", __FUNCTION__);
2962                 }
2963                 int relFence = sHandleImporter.unlock(*(halBuf.bufPtr));
2964                 if (relFence >= 0) {
2965                     halBuf.acquireFence = relFence;
2966                 }
2967             } break;
2968             default:
2969                 lk.unlock();
2970                 return onDeviceError("%s: unknown output format %x", __FUNCTION__, halBuf.format);
2971         }
2972     }  // for each buffer
2973     mScaledYu12Frames.clear();
2974 
2975     // Don't hold the lock while calling back to parent
2976     lk.unlock();
2977     Status st = parent->processCaptureResult(req);
2978     if (st != Status::OK) {
2979         return onDeviceError("%s: failed to process capture result!", __FUNCTION__);
2980     }
2981     signalRequestDone();
2982     return true;
2983 }
2984 
2985 // End ExternalCameraDeviceSession::OutputThread functions
2986 
2987 }  // namespace implementation
2988 }  // namespace device
2989 }  // namespace camera
2990 }  // namespace hardware
2991 }  // namespace android
2992