• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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             numAttempt++;
1189             if (ret < 0) {
1190                 ALOGW("%s: VIDIOC_STREAMON failed, wait 33ms and try again", __FUNCTION__);
1191                 usleep(IOCTL_RETRY_SLEEP_US);  // sleep 100 ms and try again
1192             }
1193         } while (ret < 0);
1194 
1195         if (ret < 0) {
1196             ALOGE("%s: VIDIOC_STREAMON ioctl failed: %s", __FUNCTION__, strerror(errno));
1197             return -errno;
1198         }
1199     }
1200 
1201     // Swallow first few frames after streamOn to account for bad frames from some devices
1202     for (int i = 0; i < kBadFramesAfterStreamOn; i++) {
1203         v4l2_buffer buffer{};
1204         buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1205         buffer.memory = V4L2_MEMORY_MMAP;
1206         if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_DQBUF, &buffer)) < 0) {
1207             ALOGE("%s: DQBUF fails: %s", __FUNCTION__, strerror(errno));
1208             return -errno;
1209         }
1210 
1211         if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
1212             ALOGE("%s: QBUF index %d fails: %s", __FUNCTION__, buffer.index, strerror(errno));
1213             return -errno;
1214         }
1215     }
1216 
1217     ALOGI("%s: start V4L2 streaming %dx%d@%ffps", __FUNCTION__, v4l2Fmt.width, v4l2Fmt.height, fps);
1218     mV4l2StreamingFmt = v4l2Fmt;
1219     mV4l2Streaming = true;
1220     return OK;
1221 }
1222 
dequeueV4l2FrameLocked(nsecs_t * shutterTs)1223 std::unique_ptr<V4L2Frame> ExternalCameraDeviceSession::dequeueV4l2FrameLocked(nsecs_t* shutterTs) {
1224     ATRACE_CALL();
1225     std::unique_ptr<V4L2Frame> ret = nullptr;
1226     if (shutterTs == nullptr) {
1227         ALOGE("%s: shutterTs must not be null!", __FUNCTION__);
1228         return ret;
1229     }
1230 
1231     {
1232         std::unique_lock<std::mutex> lk(mV4l2BufferLock);
1233         if (mNumDequeuedV4l2Buffers == mV4L2BufferCount) {
1234             int waitRet = waitForV4L2BufferReturnLocked(lk);
1235             if (waitRet != 0) {
1236                 return ret;
1237             }
1238         }
1239     }
1240 
1241     uint64_t lagNs = 0;
1242     v4l2_buffer buffer{};
1243     do {
1244         ATRACE_BEGIN("VIDIOC_DQBUF");
1245         buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1246         buffer.memory = V4L2_MEMORY_MMAP;
1247         if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_DQBUF, &buffer)) < 0) {
1248             ALOGE("%s: DQBUF fails: %s", __FUNCTION__, strerror(errno));
1249             return ret;
1250         }
1251         ATRACE_END();
1252 
1253         if (buffer.index >= mV4L2BufferCount) {
1254             ALOGE("%s: Invalid buffer id: %d", __FUNCTION__, buffer.index);
1255             return ret;
1256         }
1257 
1258         if (buffer.flags & V4L2_BUF_FLAG_ERROR) {
1259             ALOGE("%s: v4l2 buf error! buf flag 0x%x", __FUNCTION__, buffer.flags);
1260             // TODO: try to dequeue again
1261         }
1262 
1263         if (buffer.bytesused > mMaxV4L2BufferSize) {
1264             ALOGE("%s: v4l2 buffer bytes used: %u maximum %u", __FUNCTION__, buffer.bytesused,
1265                   mMaxV4L2BufferSize);
1266             return ret;
1267         }
1268 
1269         nsecs_t curTimeNs = systemTime(SYSTEM_TIME_MONOTONIC);
1270 
1271         if (buffer.flags & V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC) {
1272             // Ideally we should also check for V4L2_BUF_FLAG_TSTAMP_SRC_SOE, but
1273             // even V4L2_BUF_FLAG_TSTAMP_SRC_EOF is better than capture a timestamp now
1274             *shutterTs = static_cast<nsecs_t>(buffer.timestamp.tv_sec) * 1000000000LL +
1275                          buffer.timestamp.tv_usec * 1000LL;
1276         } else {
1277             *shutterTs = curTimeNs;
1278         }
1279 
1280         // The tactic only takes effect on v4l2 buffers with flag V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC.
1281         // Most USB cameras should have the feature.
1282         if (curTimeNs < *shutterTs) {
1283             lagNs = 0;
1284             ALOGW("%s: should not happen, the monotonic clock has issue, shutterTs is in the "
1285                   "future, curTimeNs %" PRId64 "  < "
1286                   "shutterTs %" PRId64 "",
1287                   __func__, curTimeNs, *shutterTs);
1288         } else {
1289             lagNs = curTimeNs - *shutterTs;
1290         }
1291 
1292         if (lagNs > mMaxLagNs) {
1293             ALOGI("%s: drop too old buffer, index %d, lag %" PRIu64 " ns > max %" PRIu64 " ns", __FUNCTION__,
1294                   buffer.index, lagNs, mMaxLagNs);
1295             int retVal = ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer);
1296             if (retVal) {
1297                 ALOGE("%s: unexpected VIDIOC_QBUF failed, retVal %d", __FUNCTION__, retVal);
1298                 return ret;
1299             }
1300         }
1301     } while (lagNs > mMaxLagNs);
1302 
1303     {
1304         std::lock_guard<std::mutex> lk(mV4l2BufferLock);
1305         mNumDequeuedV4l2Buffers++;
1306     }
1307 
1308     return std::make_unique<V4L2Frame>(mV4l2StreamingFmt.width, mV4l2StreamingFmt.height,
1309                                        mV4l2StreamingFmt.fourcc, buffer.index, mV4l2Fd.get(),
1310                                        buffer.bytesused, buffer.m.offset);
1311 }
1312 
enqueueV4l2Frame(const std::shared_ptr<V4L2Frame> & frame)1313 void ExternalCameraDeviceSession::enqueueV4l2Frame(const std::shared_ptr<V4L2Frame>& frame) {
1314     ATRACE_CALL();
1315     frame->unmap();
1316     ATRACE_BEGIN("VIDIOC_QBUF");
1317     v4l2_buffer buffer{};
1318     buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1319     buffer.memory = V4L2_MEMORY_MMAP;
1320     buffer.index = frame->mBufferIndex;
1321     if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
1322         ALOGE("%s: QBUF index %d fails: %s", __FUNCTION__, frame->mBufferIndex, strerror(errno));
1323         return;
1324     }
1325     ATRACE_END();
1326 
1327     {
1328         std::lock_guard<std::mutex> lk(mV4l2BufferLock);
1329         mNumDequeuedV4l2Buffers--;
1330     }
1331     mV4L2BufferReturned.notify_one();
1332 }
1333 
isSupported(const Stream & stream,const std::vector<SupportedV4L2Format> & supportedFormats,const ExternalCameraConfig & devCfg)1334 bool ExternalCameraDeviceSession::isSupported(
1335         const Stream& stream, const std::vector<SupportedV4L2Format>& supportedFormats,
1336         const ExternalCameraConfig& devCfg) {
1337     Dataspace ds = stream.dataSpace;
1338     PixelFormat fmt = stream.format;
1339     uint32_t width = stream.width;
1340     uint32_t height = stream.height;
1341     // TODO: check usage flags
1342 
1343     if (stream.streamType != StreamType::OUTPUT) {
1344         ALOGE("%s: does not support non-output stream type", __FUNCTION__);
1345         return false;
1346     }
1347 
1348     if (stream.rotation != StreamRotation::ROTATION_0) {
1349         ALOGE("%s: does not support stream rotation", __FUNCTION__);
1350         return false;
1351     }
1352 
1353     switch (fmt) {
1354         case PixelFormat::BLOB:
1355             if (ds != Dataspace::JFIF) {
1356                 ALOGI("%s: BLOB format does not support dataSpace %x", __FUNCTION__, ds);
1357                 return false;
1358             }
1359             break;
1360         case PixelFormat::IMPLEMENTATION_DEFINED:
1361         case PixelFormat::YCBCR_420_888:
1362         case PixelFormat::YV12:
1363             // TODO: check what dataspace we can support here.
1364             // intentional no-ops.
1365             break;
1366         case PixelFormat::Y16:
1367             if (!devCfg.depthEnabled) {
1368                 ALOGI("%s: Depth is not Enabled", __FUNCTION__);
1369                 return false;
1370             }
1371             if (!(static_cast<int32_t>(ds) & static_cast<int32_t>(Dataspace::DEPTH))) {
1372                 ALOGI("%s: Y16 supports only dataSpace DEPTH", __FUNCTION__);
1373                 return false;
1374             }
1375             break;
1376         default:
1377             ALOGI("%s: does not support format %x", __FUNCTION__, fmt);
1378             return false;
1379     }
1380 
1381     // Assume we can convert any V4L2 format to any of supported output format for now, i.e.
1382     // ignoring v4l2Fmt.fourcc for now. Might need more subtle check if we support more v4l format
1383     // in the futrue.
1384     for (const auto& v4l2Fmt : supportedFormats) {
1385         if (width == v4l2Fmt.width && height == v4l2Fmt.height) {
1386             return true;
1387         }
1388     }
1389     ALOGI("%s: resolution %dx%d is not supported", __FUNCTION__, width, height);
1390     return false;
1391 }
1392 
importBuffer(int32_t streamId,uint64_t bufId,buffer_handle_t buf,buffer_handle_t ** outBufPtr)1393 Status ExternalCameraDeviceSession::importBuffer(int32_t streamId, uint64_t bufId,
1394                                                  buffer_handle_t buf,
1395                                                  /*out*/ buffer_handle_t** outBufPtr) {
1396     Mutex::Autolock _l(mCbsLock);
1397     return importBufferLocked(streamId, bufId, buf, outBufPtr);
1398 }
1399 
importBufferLocked(int32_t streamId,uint64_t bufId,buffer_handle_t buf,buffer_handle_t ** outBufPtr)1400 Status ExternalCameraDeviceSession::importBufferLocked(int32_t streamId, uint64_t bufId,
1401                                                        buffer_handle_t buf,
1402                                                        buffer_handle_t** outBufPtr) {
1403     return importBufferImpl(mCirculatingBuffers, sHandleImporter, streamId, bufId, buf, outBufPtr);
1404 }
1405 
close()1406 ScopedAStatus ExternalCameraDeviceSession::close() {
1407     closeImpl();
1408     return fromStatus(Status::OK);
1409 }
1410 
closeImpl()1411 void ExternalCameraDeviceSession::closeImpl() {
1412     Mutex::Autolock _il(mInterfaceLock);
1413     bool closed = isClosed();
1414     if (!closed) {
1415         closeOutputThread();
1416         closeBufferRequestThread();
1417 
1418         Mutex::Autolock _l(mLock);
1419         // free all buffers
1420         {
1421             Mutex::Autolock _cbsl(mCbsLock);
1422             for (auto pair : mStreamMap) {
1423                 cleanupBuffersLocked(/*Stream ID*/ pair.first);
1424             }
1425         }
1426         v4l2StreamOffLocked();
1427         ALOGV("%s: closing V4L2 camera FD %d", __FUNCTION__, mV4l2Fd.get());
1428         mV4l2Fd.reset();
1429         mClosed = true;
1430     }
1431 }
1432 
isClosed()1433 bool ExternalCameraDeviceSession::isClosed() {
1434     Mutex::Autolock _l(mLock);
1435     return mClosed;
1436 }
1437 
repeatingRequestEnd(int32_t,const std::vector<int32_t> &)1438 ScopedAStatus ExternalCameraDeviceSession::repeatingRequestEnd(
1439         int32_t /*in_frameNumber*/, const std::vector<int32_t>& /*in_streamIds*/) {
1440     // TODO: Figure this one out.
1441     return fromStatus(Status::OK);
1442 }
1443 
v4l2StreamOffLocked()1444 int ExternalCameraDeviceSession::v4l2StreamOffLocked() {
1445     if (!mV4l2Streaming) {
1446         return OK;
1447     }
1448 
1449     {
1450         std::lock_guard<std::mutex> lk(mV4l2BufferLock);
1451         if (mNumDequeuedV4l2Buffers != 0) {
1452             ALOGE("%s: there are %zu inflight V4L buffers", __FUNCTION__, mNumDequeuedV4l2Buffers);
1453             return -1;
1454         }
1455     }
1456     mV4L2BufferCount = 0;
1457 
1458     // VIDIOC_STREAMOFF
1459     v4l2_buf_type capture_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1460     if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_STREAMOFF, &capture_type)) < 0) {
1461         ALOGE("%s: STREAMOFF failed: %s", __FUNCTION__, strerror(errno));
1462         return -errno;
1463     }
1464 
1465     // VIDIOC_REQBUFS: clear buffers
1466     v4l2_requestbuffers req_buffers{};
1467     req_buffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1468     req_buffers.memory = V4L2_MEMORY_MMAP;
1469     req_buffers.count = 0;
1470     if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_REQBUFS, &req_buffers)) < 0) {
1471         ALOGE("%s: REQBUFS failed: %s", __FUNCTION__, strerror(errno));
1472         return -errno;
1473     }
1474 
1475     mV4l2Streaming = false;
1476     return OK;
1477 }
1478 
setV4l2FpsLocked(double fps)1479 int ExternalCameraDeviceSession::setV4l2FpsLocked(double fps) {
1480     // VIDIOC_G_PARM/VIDIOC_S_PARM: set fps
1481     v4l2_streamparm streamparm = {.type = V4L2_BUF_TYPE_VIDEO_CAPTURE};
1482     // The following line checks that the driver knows about framerate get/set.
1483     int ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_G_PARM, &streamparm));
1484     if (ret != 0) {
1485         if (errno == -EINVAL) {
1486             ALOGW("%s: device does not support VIDIOC_G_PARM", __FUNCTION__);
1487         }
1488         return -errno;
1489     }
1490     // Now check if the device is able to accept a capture framerate set.
1491     if (!(streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME)) {
1492         ALOGW("%s: device does not support V4L2_CAP_TIMEPERFRAME", __FUNCTION__);
1493         return -EINVAL;
1494     }
1495 
1496     // fps is float, approximate by a fraction.
1497     const int kFrameRatePrecision = 10000;
1498     streamparm.parm.capture.timeperframe.numerator = kFrameRatePrecision;
1499     streamparm.parm.capture.timeperframe.denominator = (fps * kFrameRatePrecision);
1500 
1501     if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_S_PARM, &streamparm)) < 0) {
1502         ALOGE("%s: failed to set framerate to %f: %s", __FUNCTION__, fps, strerror(errno));
1503         return -1;
1504     }
1505 
1506     double retFps = streamparm.parm.capture.timeperframe.denominator /
1507                     static_cast<double>(streamparm.parm.capture.timeperframe.numerator);
1508     if (std::fabs(fps - retFps) > 1.0) {
1509         ALOGE("%s: expect fps %f, got %f instead", __FUNCTION__, fps, retFps);
1510         return -1;
1511     }
1512     mV4l2StreamingFps = fps;
1513     return 0;
1514 }
1515 
cleanupInflightFences(std::vector<int> & allFences,size_t numFences)1516 void ExternalCameraDeviceSession::cleanupInflightFences(std::vector<int>& allFences,
1517                                                         size_t numFences) {
1518     for (size_t j = 0; j < numFences; j++) {
1519         sHandleImporter.closeFence(allFences[j]);
1520     }
1521 }
1522 
cleanupBuffersLocked(int id)1523 void ExternalCameraDeviceSession::cleanupBuffersLocked(int id) {
1524     for (auto& pair : mCirculatingBuffers.at(id)) {
1525         sHandleImporter.freeBuffer(pair.second);
1526     }
1527     mCirculatingBuffers[id].clear();
1528     mCirculatingBuffers.erase(id);
1529 }
1530 
notifyShutter(int32_t frameNumber,nsecs_t shutterTs)1531 void ExternalCameraDeviceSession::notifyShutter(int32_t frameNumber, nsecs_t shutterTs) {
1532     NotifyMsg msg;
1533     msg.set<NotifyMsg::Tag::shutter>(ShutterMsg{
1534             .frameNumber = frameNumber,
1535             .timestamp = shutterTs,
1536     });
1537     mCallback->notify({msg});
1538 }
notifyError(int32_t frameNumber,int32_t streamId,ErrorCode ec)1539 void ExternalCameraDeviceSession::notifyError(int32_t frameNumber, int32_t streamId, ErrorCode ec) {
1540     NotifyMsg msg;
1541     msg.set<NotifyMsg::Tag::error>(ErrorMsg{
1542             .frameNumber = frameNumber,
1543             .errorStreamId = streamId,
1544             .errorCode = ec,
1545     });
1546     mCallback->notify({msg});
1547 }
1548 
invokeProcessCaptureResultCallback(std::vector<CaptureResult> & results,bool tryWriteFmq)1549 void ExternalCameraDeviceSession::invokeProcessCaptureResultCallback(
1550         std::vector<CaptureResult>& results, bool tryWriteFmq) {
1551     if (mProcessCaptureResultLock.tryLock() != OK) {
1552         const nsecs_t NS_TO_SECOND = 1000000000;
1553         ALOGV("%s: previous call is not finished! waiting 1s...", __FUNCTION__);
1554         if (mProcessCaptureResultLock.timedLock(/* 1s */ NS_TO_SECOND) != OK) {
1555             ALOGE("%s: cannot acquire lock in 1s, cannot proceed", __FUNCTION__);
1556             return;
1557         }
1558     }
1559     if (tryWriteFmq && mResultMetadataQueue->availableToWrite() > 0) {
1560         for (CaptureResult& result : results) {
1561             CameraMetadata& md = result.result;
1562             if (!md.metadata.empty()) {
1563                 if (mResultMetadataQueue->write(reinterpret_cast<int8_t*>(md.metadata.data()),
1564                                                 md.metadata.size())) {
1565                     result.fmqResultSize = md.metadata.size();
1566                     md.metadata.resize(0);
1567                 } else {
1568                     ALOGW("%s: couldn't utilize fmq, fall back to hwbinder", __FUNCTION__);
1569                     result.fmqResultSize = 0;
1570                 }
1571             } else {
1572                 result.fmqResultSize = 0;
1573             }
1574         }
1575     }
1576     auto status = mCallback->processCaptureResult(results);
1577     if (!status.isOk()) {
1578         ALOGE("%s: processCaptureResult ERROR : %d:%d", __FUNCTION__, status.getExceptionCode(),
1579               status.getServiceSpecificError());
1580     }
1581 
1582     mProcessCaptureResultLock.unlock();
1583 }
1584 
waitForV4L2BufferReturnLocked(std::unique_lock<std::mutex> & lk)1585 int ExternalCameraDeviceSession::waitForV4L2BufferReturnLocked(std::unique_lock<std::mutex>& lk) {
1586     ATRACE_CALL();
1587     auto timeout = std::chrono::seconds(kBufferWaitTimeoutSec);
1588     mLock.unlock();
1589     auto st = mV4L2BufferReturned.wait_for(lk, timeout);
1590     // Here we introduce an order where mV4l2BufferLock is acquired before mLock, while
1591     // the normal lock acquisition order is reversed. This is fine because in most of
1592     // cases we are protected by mInterfaceLock. The only thread that can cause deadlock
1593     // is the OutputThread, where we do need to make sure we don't acquire mLock then
1594     // mV4l2BufferLock
1595     mLock.lock();
1596     if (st == std::cv_status::timeout) {
1597         ALOGE("%s: wait for V4L2 buffer return timeout!", __FUNCTION__);
1598         return -1;
1599     }
1600     return 0;
1601 }
1602 
supportOfflineLocked(int32_t streamId)1603 bool ExternalCameraDeviceSession::supportOfflineLocked(int32_t streamId) {
1604     const Stream& stream = mStreamMap[streamId];
1605     if (stream.format == PixelFormat::BLOB &&
1606         static_cast<int32_t>(stream.dataSpace) == static_cast<int32_t>(Dataspace::JFIF)) {
1607         return true;
1608     }
1609     // TODO: support YUV output stream?
1610     return false;
1611 }
1612 
canDropRequest(const std::vector<int32_t> & offlineStreams,std::shared_ptr<HalRequest> halReq)1613 bool ExternalCameraDeviceSession::canDropRequest(const std::vector<int32_t>& offlineStreams,
1614                                                  std::shared_ptr<HalRequest> halReq) {
1615     for (const auto& buffer : halReq->buffers) {
1616         for (auto offlineStreamId : offlineStreams) {
1617             if (buffer.streamId == offlineStreamId) {
1618                 return false;
1619             }
1620         }
1621     }
1622     // Only drop a request completely if it has no offline output
1623     return true;
1624 }
1625 
fillOfflineSessionInfo(const std::vector<int32_t> & offlineStreams,std::deque<std::shared_ptr<HalRequest>> & offlineReqs,const std::map<int,CirculatingBuffers> & circulatingBuffers,CameraOfflineSessionInfo * info)1626 void ExternalCameraDeviceSession::fillOfflineSessionInfo(
1627         const std::vector<int32_t>& offlineStreams,
1628         std::deque<std::shared_ptr<HalRequest>>& offlineReqs,
1629         const std::map<int, CirculatingBuffers>& circulatingBuffers,
1630         CameraOfflineSessionInfo* info) {
1631     if (info == nullptr) {
1632         ALOGE("%s: output info must not be null!", __FUNCTION__);
1633         return;
1634     }
1635 
1636     info->offlineStreams.resize(offlineStreams.size());
1637     info->offlineRequests.resize(offlineReqs.size());
1638 
1639     // Fill in offline reqs and count outstanding buffers
1640     for (size_t i = 0; i < offlineReqs.size(); i++) {
1641         info->offlineRequests[i].frameNumber = offlineReqs[i]->frameNumber;
1642         info->offlineRequests[i].pendingStreams.resize(offlineReqs[i]->buffers.size());
1643         for (size_t bIdx = 0; bIdx < offlineReqs[i]->buffers.size(); bIdx++) {
1644             int32_t streamId = offlineReqs[i]->buffers[bIdx].streamId;
1645             info->offlineRequests[i].pendingStreams[bIdx] = streamId;
1646         }
1647     }
1648 
1649     for (size_t i = 0; i < offlineStreams.size(); i++) {
1650         int32_t streamId = offlineStreams[i];
1651         info->offlineStreams[i].id = streamId;
1652         // outstanding buffers are 0 since we are doing hal buffer management and
1653         // offline session will ask for those buffers later
1654         info->offlineStreams[i].numOutstandingBuffers = 0;
1655         const CirculatingBuffers& bufIdMap = circulatingBuffers.at(streamId);
1656         info->offlineStreams[i].circulatingBufferIds.resize(bufIdMap.size());
1657         size_t bIdx = 0;
1658         for (const auto& pair : bufIdMap) {
1659             // Fill in bufferId
1660             info->offlineStreams[i].circulatingBufferIds[bIdx++] = pair.first;
1661         }
1662     }
1663 }
1664 
isStreamCombinationSupported(const StreamConfiguration & config,const std::vector<SupportedV4L2Format> & supportedFormats,const ExternalCameraConfig & devCfg)1665 Status ExternalCameraDeviceSession::isStreamCombinationSupported(
1666         const StreamConfiguration& config, const std::vector<SupportedV4L2Format>& supportedFormats,
1667         const ExternalCameraConfig& devCfg) {
1668     if (config.operationMode != StreamConfigurationMode::NORMAL_MODE) {
1669         ALOGE("%s: unsupported operation mode: %d", __FUNCTION__, config.operationMode);
1670         return Status::ILLEGAL_ARGUMENT;
1671     }
1672 
1673     if (config.streams.size() == 0) {
1674         ALOGE("%s: cannot configure zero stream", __FUNCTION__);
1675         return Status::ILLEGAL_ARGUMENT;
1676     }
1677 
1678     int numProcessedStream = 0;
1679     int numStallStream = 0;
1680     for (const auto& stream : config.streams) {
1681         // Check if the format/width/height combo is supported
1682         if (!isSupported(stream, supportedFormats, devCfg)) {
1683             return Status::ILLEGAL_ARGUMENT;
1684         }
1685         if (stream.format == PixelFormat::BLOB) {
1686             numStallStream++;
1687         } else {
1688             numProcessedStream++;
1689         }
1690     }
1691 
1692     if (numProcessedStream > kMaxProcessedStream) {
1693         ALOGE("%s: too many processed streams (expect <= %d, got %d)", __FUNCTION__,
1694               kMaxProcessedStream, numProcessedStream);
1695         return Status::ILLEGAL_ARGUMENT;
1696     }
1697 
1698     if (numStallStream > kMaxStallStream) {
1699         ALOGE("%s: too many stall streams (expect <= %d, got %d)", __FUNCTION__, kMaxStallStream,
1700               numStallStream);
1701         return Status::ILLEGAL_ARGUMENT;
1702     }
1703 
1704     return Status::OK;
1705 }
updateBufferCaches(const std::vector<BufferCache> & cachesToRemove)1706 void ExternalCameraDeviceSession::updateBufferCaches(
1707         const std::vector<BufferCache>& cachesToRemove) {
1708     Mutex::Autolock _l(mCbsLock);
1709     for (auto& cache : cachesToRemove) {
1710         auto cbsIt = mCirculatingBuffers.find(cache.streamId);
1711         if (cbsIt == mCirculatingBuffers.end()) {
1712             // The stream could have been removed
1713             continue;
1714         }
1715         CirculatingBuffers& cbs = cbsIt->second;
1716         auto it = cbs.find(cache.bufferId);
1717         if (it != cbs.end()) {
1718             sHandleImporter.freeBuffer(it->second);
1719             cbs.erase(it);
1720         } else {
1721             ALOGE("%s: stream %d buffer %" PRIu64 " is not cached", __FUNCTION__, cache.streamId,
1722                   cache.bufferId);
1723         }
1724     }
1725 }
1726 
processCaptureRequestError(const std::shared_ptr<HalRequest> & req,std::vector<NotifyMsg> * outMsgs,std::vector<CaptureResult> * outResults)1727 Status ExternalCameraDeviceSession::processCaptureRequestError(
1728         const std::shared_ptr<HalRequest>& req, std::vector<NotifyMsg>* outMsgs,
1729         std::vector<CaptureResult>* outResults) {
1730     ATRACE_CALL();
1731     // Return V4L2 buffer to V4L2 buffer queue
1732     std::shared_ptr<V4L2Frame> v4l2Frame = std::static_pointer_cast<V4L2Frame>(req->frameIn);
1733     enqueueV4l2Frame(v4l2Frame);
1734 
1735     if (outMsgs == nullptr) {
1736         notifyShutter(req->frameNumber, req->shutterTs);
1737         notifyError(/*frameNum*/ req->frameNumber, /*stream*/ -1, ErrorCode::ERROR_REQUEST);
1738     } else {
1739         NotifyMsg shutter;
1740         shutter.set<NotifyMsg::Tag::shutter>(
1741                 ShutterMsg{.frameNumber = req->frameNumber, .timestamp = req->shutterTs});
1742 
1743         NotifyMsg error;
1744         error.set<NotifyMsg::Tag::error>(ErrorMsg{.frameNumber = req->frameNumber,
1745                                                   .errorStreamId = -1,
1746                                                   .errorCode = ErrorCode::ERROR_REQUEST});
1747         outMsgs->push_back(shutter);
1748         outMsgs->push_back(error);
1749     }
1750 
1751     // Fill output buffers
1752     CaptureResult result;
1753     result.frameNumber = req->frameNumber;
1754     result.partialResult = 1;
1755     result.inputBuffer.streamId = -1;
1756     result.outputBuffers.resize(req->buffers.size());
1757     for (size_t i = 0; i < req->buffers.size(); i++) {
1758         result.outputBuffers[i].streamId = req->buffers[i].streamId;
1759         result.outputBuffers[i].bufferId = req->buffers[i].bufferId;
1760         result.outputBuffers[i].status = BufferStatus::ERROR;
1761         if (req->buffers[i].acquireFence >= 0) {
1762             // numFds = 0 for error
1763             native_handle_t* handle = native_handle_create(/*numFds*/ 0, /*numInts*/ 0);
1764             result.outputBuffers[i].releaseFence = android::dupToAidl(handle);
1765             native_handle_delete(handle);
1766         }
1767     }
1768 
1769     // update inflight records
1770     {
1771         std::lock_guard<std::mutex> lk(mInflightFramesLock);
1772         mInflightFrames.erase(req->frameNumber);
1773     }
1774 
1775     if (outResults == nullptr) {
1776         // Callback into framework
1777         std::vector<CaptureResult> results(1);
1778         results[0] = std::move(result);
1779         invokeProcessCaptureResultCallback(results, /* tryWriteFmq */ true);
1780         freeReleaseFences(results);
1781     } else {
1782         outResults->push_back(std::move(result));
1783     }
1784     return Status::OK;
1785 }
1786 
processCaptureResult(std::shared_ptr<HalRequest> & req)1787 Status ExternalCameraDeviceSession::processCaptureResult(std::shared_ptr<HalRequest>& req) {
1788     ATRACE_CALL();
1789     // Return V4L2 buffer to V4L2 buffer queue
1790     std::shared_ptr<V4L2Frame> v4l2Frame = std::static_pointer_cast<V4L2Frame>(req->frameIn);
1791     enqueueV4l2Frame(v4l2Frame);
1792 
1793     // NotifyShutter
1794     notifyShutter(req->frameNumber, req->shutterTs);
1795 
1796     // Fill output buffers;
1797     std::vector<CaptureResult> results(1);
1798     CaptureResult& result = results[0];
1799     result.frameNumber = req->frameNumber;
1800     result.partialResult = 1;
1801     result.inputBuffer.streamId = -1;
1802     result.outputBuffers.resize(req->buffers.size());
1803     for (size_t i = 0; i < req->buffers.size(); i++) {
1804         result.outputBuffers[i].streamId = req->buffers[i].streamId;
1805         result.outputBuffers[i].bufferId = req->buffers[i].bufferId;
1806         if (req->buffers[i].fenceTimeout) {
1807             result.outputBuffers[i].status = BufferStatus::ERROR;
1808             if (req->buffers[i].acquireFence >= 0) {
1809                 native_handle_t* handle = native_handle_create(/*numFds*/ 1, /*numInts*/ 0);
1810                 handle->data[0] = req->buffers[i].acquireFence;
1811                 result.outputBuffers[i].releaseFence = android::dupToAidl(handle);
1812                 native_handle_delete(handle);
1813             }
1814             notifyError(req->frameNumber, req->buffers[i].streamId, ErrorCode::ERROR_BUFFER);
1815         } else {
1816             result.outputBuffers[i].status = BufferStatus::OK;
1817             // TODO: refactor
1818             if (req->buffers[i].acquireFence >= 0) {
1819                 native_handle_t* handle = native_handle_create(/*numFds*/ 1, /*numInts*/ 0);
1820                 handle->data[0] = req->buffers[i].acquireFence;
1821                 result.outputBuffers[i].releaseFence = android::dupToAidl(handle);
1822                 native_handle_delete(handle);
1823             }
1824         }
1825     }
1826 
1827     // Fill capture result metadata
1828     fillCaptureResult(req->setting, req->shutterTs);
1829     const camera_metadata_t* rawResult = req->setting.getAndLock();
1830     convertToAidl(rawResult, &result.result);
1831     req->setting.unlock(rawResult);
1832 
1833     // update inflight records
1834     {
1835         std::lock_guard<std::mutex> lk(mInflightFramesLock);
1836         mInflightFrames.erase(req->frameNumber);
1837     }
1838 
1839     // Callback into framework
1840     invokeProcessCaptureResultCallback(results, /* tryWriteFmq */ true);
1841     freeReleaseFences(results);
1842     return Status::OK;
1843 }
1844 
getJpegBufferSize(int32_t width,int32_t height) const1845 ssize_t ExternalCameraDeviceSession::getJpegBufferSize(int32_t width, int32_t height) const {
1846     // Constant from camera3.h
1847     const ssize_t kMinJpegBufferSize = 256 * 1024 + sizeof(CameraBlob);
1848     // Get max jpeg size (area-wise).
1849     if (mMaxJpegResolution.width == 0) {
1850         ALOGE("%s: No supported JPEG stream", __FUNCTION__);
1851         return BAD_VALUE;
1852     }
1853 
1854     // Get max jpeg buffer size
1855     ssize_t maxJpegBufferSize = 0;
1856     camera_metadata_ro_entry jpegBufMaxSize = mCameraCharacteristics.find(ANDROID_JPEG_MAX_SIZE);
1857     if (jpegBufMaxSize.count == 0) {
1858         ALOGE("%s: Can't find maximum JPEG size in static metadata!", __FUNCTION__);
1859         return BAD_VALUE;
1860     }
1861     maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
1862 
1863     if (maxJpegBufferSize <= kMinJpegBufferSize) {
1864         ALOGE("%s: ANDROID_JPEG_MAX_SIZE (%zd) <= kMinJpegBufferSize (%zd)", __FUNCTION__,
1865               maxJpegBufferSize, kMinJpegBufferSize);
1866         return BAD_VALUE;
1867     }
1868 
1869     // Calculate final jpeg buffer size for the given resolution.
1870     float scaleFactor =
1871             ((float)(width * height)) / (mMaxJpegResolution.width * mMaxJpegResolution.height);
1872     ssize_t jpegBufferSize =
1873             scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) + kMinJpegBufferSize;
1874     if (jpegBufferSize > maxJpegBufferSize) {
1875         jpegBufferSize = maxJpegBufferSize;
1876     }
1877 
1878     return jpegBufferSize;
1879 }
dump(int fd,const char **,uint32_t)1880 binder_status_t ExternalCameraDeviceSession::dump(int fd, const char** /*args*/,
1881                                                   uint32_t /*numArgs*/) {
1882     bool intfLocked = tryLock(mInterfaceLock);
1883     if (!intfLocked) {
1884         dprintf(fd, "!! ExternalCameraDeviceSession interface may be deadlocked !!\n");
1885     }
1886 
1887     if (isClosed()) {
1888         dprintf(fd, "External camera %s is closed\n", mCameraId.c_str());
1889         return STATUS_OK;
1890     }
1891 
1892     bool streaming = false;
1893     size_t v4L2BufferCount = 0;
1894     SupportedV4L2Format streamingFmt;
1895     {
1896         bool sessionLocked = tryLock(mLock);
1897         if (!sessionLocked) {
1898             dprintf(fd, "!! ExternalCameraDeviceSession mLock may be deadlocked !!\n");
1899         }
1900         streaming = mV4l2Streaming;
1901         streamingFmt = mV4l2StreamingFmt;
1902         v4L2BufferCount = mV4L2BufferCount;
1903 
1904         if (sessionLocked) {
1905             mLock.unlock();
1906         }
1907     }
1908 
1909     std::unordered_set<uint32_t> inflightFrames;
1910     {
1911         bool iffLocked = tryLock(mInflightFramesLock);
1912         if (!iffLocked) {
1913             dprintf(fd,
1914                     "!! ExternalCameraDeviceSession mInflightFramesLock may be deadlocked !!\n");
1915         }
1916         inflightFrames = mInflightFrames;
1917         if (iffLocked) {
1918             mInflightFramesLock.unlock();
1919         }
1920     }
1921 
1922     dprintf(fd, "External camera %s V4L2 FD %d, cropping type %s, %s\n", mCameraId.c_str(),
1923             mV4l2Fd.get(), (mCroppingType == VERTICAL) ? "vertical" : "horizontal",
1924             streaming ? "streaming" : "not streaming");
1925 
1926     if (streaming) {
1927         // TODO: dump fps later
1928         dprintf(fd, "Current V4L2 format %c%c%c%c %dx%d @ %ffps\n", streamingFmt.fourcc & 0xFF,
1929                 (streamingFmt.fourcc >> 8) & 0xFF, (streamingFmt.fourcc >> 16) & 0xFF,
1930                 (streamingFmt.fourcc >> 24) & 0xFF, streamingFmt.width, streamingFmt.height,
1931                 mV4l2StreamingFps);
1932 
1933         size_t numDequeuedV4l2Buffers = 0;
1934         {
1935             std::lock_guard<std::mutex> lk(mV4l2BufferLock);
1936             numDequeuedV4l2Buffers = mNumDequeuedV4l2Buffers;
1937         }
1938         dprintf(fd, "V4L2 buffer queue size %zu, dequeued %zu\n", v4L2BufferCount,
1939                 numDequeuedV4l2Buffers);
1940     }
1941 
1942     dprintf(fd, "In-flight frames (not sorted):");
1943     for (const auto& frameNumber : inflightFrames) {
1944         dprintf(fd, "%d, ", frameNumber);
1945     }
1946     dprintf(fd, "\n");
1947     mOutputThread->dump(fd);
1948     dprintf(fd, "\n");
1949 
1950     if (intfLocked) {
1951         mInterfaceLock.unlock();
1952     }
1953 
1954     return STATUS_OK;
1955 }
1956 
1957 // Start ExternalCameraDeviceSession::BufferRequestThread functions
BufferRequestThread(std::weak_ptr<OutputThreadInterface> parent,std::shared_ptr<ICameraDeviceCallback> callbacks)1958 ExternalCameraDeviceSession::BufferRequestThread::BufferRequestThread(
1959         std::weak_ptr<OutputThreadInterface> parent,
1960         std::shared_ptr<ICameraDeviceCallback> callbacks)
1961     : mParent(parent), mCallbacks(callbacks) {}
1962 
requestBufferStart(const std::vector<HalStreamBuffer> & bufReqs)1963 int ExternalCameraDeviceSession::BufferRequestThread::requestBufferStart(
1964         const std::vector<HalStreamBuffer>& bufReqs) {
1965     if (bufReqs.empty()) {
1966         ALOGE("%s: bufReqs is empty!", __FUNCTION__);
1967         return -1;
1968     }
1969 
1970     {
1971         std::lock_guard<std::mutex> lk(mLock);
1972         if (mRequestingBuffer) {
1973             ALOGE("%s: BufferRequestThread does not support more than one concurrent request!",
1974                   __FUNCTION__);
1975             return -1;
1976         }
1977 
1978         mBufferReqs = bufReqs;
1979         mRequestingBuffer = true;
1980     }
1981     mRequestCond.notify_one();
1982     return 0;
1983 }
1984 
waitForBufferRequestDone(std::vector<HalStreamBuffer> * outBufReqs)1985 int ExternalCameraDeviceSession::BufferRequestThread::waitForBufferRequestDone(
1986         std::vector<HalStreamBuffer>* outBufReqs) {
1987     std::unique_lock<std::mutex> lk(mLock);
1988     if (!mRequestingBuffer) {
1989         ALOGE("%s: no pending buffer request!", __FUNCTION__);
1990         return -1;
1991     }
1992 
1993     if (mPendingReturnBufferReqs.empty()) {
1994         std::chrono::milliseconds timeout = std::chrono::milliseconds(kReqProcTimeoutMs);
1995         auto st = mRequestDoneCond.wait_for(lk, timeout);
1996         if (st == std::cv_status::timeout) {
1997             mRequestingBuffer = false;
1998             ALOGE("%s: wait for buffer request finish timeout!", __FUNCTION__);
1999             return -1;
2000         }
2001 
2002         if (mPendingReturnBufferReqs.empty()) {
2003             mRequestingBuffer = false;
2004             ALOGE("%s: cameraservice did not return any buffers!", __FUNCTION__);
2005             return -1;
2006         }
2007     }
2008     mRequestingBuffer = false;
2009     *outBufReqs = std::move(mPendingReturnBufferReqs);
2010     mPendingReturnBufferReqs.clear();
2011     return 0;
2012 }
2013 
waitForNextRequest()2014 void ExternalCameraDeviceSession::BufferRequestThread::waitForNextRequest() {
2015     ATRACE_CALL();
2016     std::unique_lock<std::mutex> lk(mLock);
2017     int waitTimes = 0;
2018     while (mBufferReqs.empty()) {
2019         if (exitPending()) {
2020             return;
2021         }
2022         auto timeout = std::chrono::milliseconds(kReqWaitTimeoutMs);
2023         auto st = mRequestCond.wait_for(lk, timeout);
2024         if (st == std::cv_status::timeout) {
2025             waitTimes++;
2026             if (waitTimes == kReqWaitTimesWarn) {
2027                 // BufferRequestThread just wait forever for new buffer request
2028                 // But it will print some periodic warning indicating it's waiting
2029                 ALOGV("%s: still waiting for new buffer request", __FUNCTION__);
2030                 waitTimes = 0;
2031             }
2032         }
2033     }
2034 
2035     // Fill in BufferRequest
2036     mHalBufferReqs.resize(mBufferReqs.size());
2037     for (size_t i = 0; i < mHalBufferReqs.size(); i++) {
2038         mHalBufferReqs[i].streamId = mBufferReqs[i].streamId;
2039         mHalBufferReqs[i].numBuffersRequested = 1;
2040     }
2041 }
2042 
threadLoop()2043 bool ExternalCameraDeviceSession::BufferRequestThread::threadLoop() {
2044     waitForNextRequest();
2045     if (exitPending()) {
2046         return false;
2047     }
2048 
2049     ATRACE_BEGIN("AIDL requestStreamBuffers");
2050     BufferRequestStatus status;
2051     std::vector<StreamBufferRet> bufRets;
2052     ScopedAStatus ret = mCallbacks->requestStreamBuffers(mHalBufferReqs, &bufRets, &status);
2053     if (!ret.isOk()) {
2054         ALOGE("%s: Transaction error: %d:%d", __FUNCTION__, ret.getExceptionCode(),
2055               ret.getServiceSpecificError());
2056         mBufferReqs.clear();
2057         mRequestDoneCond.notify_one();
2058         return false;
2059     }
2060 
2061     std::unique_lock<std::mutex> lk(mLock);
2062     if (status == BufferRequestStatus::OK || status == BufferRequestStatus::FAILED_PARTIAL) {
2063         if (bufRets.size() != mHalBufferReqs.size()) {
2064             ALOGE("%s: expect %zu buffer requests returned, only got %zu", __FUNCTION__,
2065                   mHalBufferReqs.size(), bufRets.size());
2066             mBufferReqs.clear();
2067             lk.unlock();
2068             mRequestDoneCond.notify_one();
2069             return false;
2070         }
2071 
2072         auto parent = mParent.lock();
2073         if (parent == nullptr) {
2074             ALOGE("%s: session has been disconnected!", __FUNCTION__);
2075             mBufferReqs.clear();
2076             lk.unlock();
2077             mRequestDoneCond.notify_one();
2078             return false;
2079         }
2080 
2081         std::vector<int> importedFences;
2082         importedFences.resize(bufRets.size());
2083         bool hasError = false;
2084         for (size_t i = 0; i < bufRets.size(); i++) {
2085             int streamId = bufRets[i].streamId;
2086             switch (bufRets[i].val.getTag()) {
2087                 case StreamBuffersVal::Tag::error:
2088                     continue;
2089                 case StreamBuffersVal::Tag::buffers: {
2090                     const std::vector<StreamBuffer>& hBufs =
2091                             bufRets[i].val.get<StreamBuffersVal::Tag::buffers>();
2092                     if (hBufs.size() != 1) {
2093                         ALOGE("%s: expect 1 buffer returned, got %zu!", __FUNCTION__, hBufs.size());
2094                         hasError = true;
2095                         break;
2096                     }
2097                     const StreamBuffer& hBuf = hBufs[0];
2098 
2099                     mBufferReqs[i].bufferId = hBuf.bufferId;
2100                     // TODO: create a batch import API so we don't need to lock/unlock mCbsLock
2101                     // repeatedly?
2102                     lk.unlock();
2103                     native_handle_t* h = makeFromAidl(hBuf.buffer);
2104                     Status s = parent->importBuffer(streamId, hBuf.bufferId, h,
2105                                                     /*out*/ &mBufferReqs[i].bufPtr);
2106                     native_handle_delete(h);
2107                     lk.lock();
2108 
2109                     if (s != Status::OK) {
2110                         ALOGE("%s: stream %d import buffer failed!", __FUNCTION__, streamId);
2111                         cleanupInflightFences(importedFences, i - 1);
2112                         hasError = true;
2113                         break;
2114                     }
2115                     h = makeFromAidl(hBuf.acquireFence);
2116                     if (!sHandleImporter.importFence(h, mBufferReqs[i].acquireFence)) {
2117                         ALOGE("%s: stream %d import fence failed!", __FUNCTION__, streamId);
2118                         cleanupInflightFences(importedFences, i - 1);
2119                         native_handle_delete(h);
2120                         hasError = true;
2121                         break;
2122                     }
2123                     native_handle_delete(h);
2124                     importedFences[i] = mBufferReqs[i].acquireFence;
2125                 } break;
2126                 default:
2127                     ALOGE("%s: Unknown StreamBuffersVal!", __FUNCTION__);
2128                     hasError = true;
2129                     break;
2130             }
2131             if (hasError) {
2132                 mBufferReqs.clear();
2133                 lk.unlock();
2134                 mRequestDoneCond.notify_one();
2135                 return true;
2136             }
2137         }
2138     } else {
2139         ALOGE("%s: requestStreamBuffers call failed!", __FUNCTION__);
2140         mBufferReqs.clear();
2141         lk.unlock();
2142         mRequestDoneCond.notify_one();
2143         return true;
2144     }
2145 
2146     mPendingReturnBufferReqs = std::move(mBufferReqs);
2147     mBufferReqs.clear();
2148 
2149     lk.unlock();
2150     mRequestDoneCond.notify_one();
2151     return true;
2152 }
2153 
2154 // End ExternalCameraDeviceSession::BufferRequestThread functions
2155 
2156 // Start ExternalCameraDeviceSession::OutputThread functions
2157 
OutputThread(std::weak_ptr<OutputThreadInterface> parent,CroppingType ct,const common::V1_0::helper::CameraMetadata & chars,std::shared_ptr<BufferRequestThread> bufReqThread)2158 ExternalCameraDeviceSession::OutputThread::OutputThread(
2159         std::weak_ptr<OutputThreadInterface> parent, CroppingType ct,
2160         const common::V1_0::helper::CameraMetadata& chars,
2161         std::shared_ptr<BufferRequestThread> bufReqThread)
2162     : mParent(parent),
2163       mCroppingType(ct),
2164       mCameraCharacteristics(chars),
2165       mBufferRequestThread(bufReqThread) {}
2166 
~OutputThread()2167 ExternalCameraDeviceSession::OutputThread::~OutputThread() {}
2168 
allocateIntermediateBuffers(const Size & v4lSize,const Size & thumbSize,const std::vector<Stream> & streams,uint32_t blobBufferSize)2169 Status ExternalCameraDeviceSession::OutputThread::allocateIntermediateBuffers(
2170         const Size& v4lSize, const Size& thumbSize, const std::vector<Stream>& streams,
2171         uint32_t blobBufferSize) {
2172     std::lock_guard<std::mutex> lk(mBufferLock);
2173     if (!mScaledYu12Frames.empty()) {
2174         ALOGE("%s: intermediate buffer pool has %zu inflight buffers! (expect 0)", __FUNCTION__,
2175               mScaledYu12Frames.size());
2176         return Status::INTERNAL_ERROR;
2177     }
2178 
2179     // Allocating intermediate YU12 frame
2180     if (mYu12Frame == nullptr || mYu12Frame->mWidth != v4lSize.width ||
2181         mYu12Frame->mHeight != v4lSize.height) {
2182         mYu12Frame.reset();
2183         mYu12Frame = std::make_shared<AllocatedFrame>(v4lSize.width, v4lSize.height);
2184         int ret = mYu12Frame->allocate(&mYu12FrameLayout);
2185         if (ret != 0) {
2186             ALOGE("%s: allocating YU12 frame failed!", __FUNCTION__);
2187             return Status::INTERNAL_ERROR;
2188         }
2189     }
2190 
2191     // Allocating intermediate YU12 thumbnail frame
2192     if (mYu12ThumbFrame == nullptr || mYu12ThumbFrame->mWidth != thumbSize.width ||
2193         mYu12ThumbFrame->mHeight != thumbSize.height) {
2194         mYu12ThumbFrame.reset();
2195         mYu12ThumbFrame = std::make_shared<AllocatedFrame>(thumbSize.width, thumbSize.height);
2196         int ret = mYu12ThumbFrame->allocate(&mYu12ThumbFrameLayout);
2197         if (ret != 0) {
2198             ALOGE("%s: allocating YU12 thumb frame failed!", __FUNCTION__);
2199             return Status::INTERNAL_ERROR;
2200         }
2201     }
2202 
2203     // Allocating scaled buffers
2204     for (const auto& stream : streams) {
2205         Size sz = {stream.width, stream.height};
2206         if (sz == v4lSize) {
2207             continue;  // Don't need an intermediate buffer same size as v4lBuffer
2208         }
2209         if (mIntermediateBuffers.count(sz) == 0) {
2210             // Create new intermediate buffer
2211             std::shared_ptr<AllocatedFrame> buf =
2212                     std::make_shared<AllocatedFrame>(stream.width, stream.height);
2213             int ret = buf->allocate();
2214             if (ret != 0) {
2215                 ALOGE("%s: allocating intermediate YU12 frame %dx%d failed!", __FUNCTION__,
2216                       stream.width, stream.height);
2217                 return Status::INTERNAL_ERROR;
2218             }
2219             mIntermediateBuffers[sz] = buf;
2220         }
2221     }
2222 
2223     // Remove unconfigured buffers
2224     auto it = mIntermediateBuffers.begin();
2225     while (it != mIntermediateBuffers.end()) {
2226         bool configured = false;
2227         auto sz = it->first;
2228         for (const auto& stream : streams) {
2229             if (stream.width == sz.width && stream.height == sz.height) {
2230                 configured = true;
2231                 break;
2232             }
2233         }
2234         if (configured) {
2235             it++;
2236         } else {
2237             it = mIntermediateBuffers.erase(it);
2238         }
2239     }
2240 
2241     // Allocate mute test pattern frame
2242     mMuteTestPatternFrame.resize(mYu12Frame->mWidth * mYu12Frame->mHeight * 3);
2243 
2244     mBlobBufferSize = blobBufferSize;
2245     return Status::OK;
2246 }
2247 
submitRequest(const std::shared_ptr<HalRequest> & req)2248 Status ExternalCameraDeviceSession::OutputThread::submitRequest(
2249         const std::shared_ptr<HalRequest>& req) {
2250     std::unique_lock<std::mutex> lk(mRequestListLock);
2251     mRequestList.push_back(req);
2252     lk.unlock();
2253     mRequestCond.notify_one();
2254     return Status::OK;
2255 }
2256 
flush()2257 void ExternalCameraDeviceSession::OutputThread::flush() {
2258     ATRACE_CALL();
2259     auto parent = mParent.lock();
2260     if (parent == nullptr) {
2261         ALOGE("%s: session has been disconnected!", __FUNCTION__);
2262         return;
2263     }
2264 
2265     std::unique_lock<std::mutex> lk(mRequestListLock);
2266     std::list<std::shared_ptr<HalRequest>> reqs = std::move(mRequestList);
2267     mRequestList.clear();
2268     if (mProcessingRequest) {
2269         auto timeout = std::chrono::seconds(kFlushWaitTimeoutSec);
2270         auto st = mRequestDoneCond.wait_for(lk, timeout);
2271         if (st == std::cv_status::timeout) {
2272             ALOGE("%s: wait for inflight request finish timeout!", __FUNCTION__);
2273         }
2274     }
2275 
2276     ALOGV("%s: flushing inflight requests", __FUNCTION__);
2277     lk.unlock();
2278     for (const auto& req : reqs) {
2279         parent->processCaptureRequestError(req);
2280     }
2281 }
2282 
dump(int fd)2283 void ExternalCameraDeviceSession::OutputThread::dump(int fd) {
2284     std::lock_guard<std::mutex> lk(mRequestListLock);
2285     if (mProcessingRequest) {
2286         dprintf(fd, "OutputThread processing frame %d\n", mProcessingFrameNumber);
2287     } else {
2288         dprintf(fd, "OutputThread not processing any frames\n");
2289     }
2290     dprintf(fd, "OutputThread request list contains frame: ");
2291     for (const auto& req : mRequestList) {
2292         dprintf(fd, "%d, ", req->frameNumber);
2293     }
2294     dprintf(fd, "\n");
2295 }
2296 
setExifMakeModel(const std::string & make,const std::string & model)2297 void ExternalCameraDeviceSession::OutputThread::setExifMakeModel(const std::string& make,
2298                                                                  const std::string& model) {
2299     mExifMake = make;
2300     mExifModel = model;
2301 }
2302 
2303 std::list<std::shared_ptr<HalRequest>>
switchToOffline()2304 ExternalCameraDeviceSession::OutputThread::switchToOffline() {
2305     ATRACE_CALL();
2306     auto parent = mParent.lock();
2307     if (parent == nullptr) {
2308         ALOGE("%s: session has been disconnected!", __FUNCTION__);
2309         return {};
2310     }
2311 
2312     std::unique_lock<std::mutex> lk(mRequestListLock);
2313     std::list<std::shared_ptr<HalRequest>> reqs = std::move(mRequestList);
2314     mRequestList.clear();
2315     if (mProcessingRequest) {
2316         auto timeout = std::chrono::seconds(kFlushWaitTimeoutSec);
2317         auto st = mRequestDoneCond.wait_for(lk, timeout);
2318         if (st == std::cv_status::timeout) {
2319             ALOGE("%s: wait for inflight request finish timeout!", __FUNCTION__);
2320         }
2321     }
2322     lk.unlock();
2323     clearIntermediateBuffers();
2324     ALOGV("%s: returning %zu request for offline processing", __FUNCTION__, reqs.size());
2325     return reqs;
2326 }
2327 
requestBufferStart(const std::vector<HalStreamBuffer> & bufs)2328 int ExternalCameraDeviceSession::OutputThread::requestBufferStart(
2329         const std::vector<HalStreamBuffer>& bufs) {
2330     if (mBufferRequestThread == nullptr) {
2331         return 0;
2332     }
2333     return mBufferRequestThread->requestBufferStart(bufs);
2334 }
2335 
waitForBufferRequestDone(std::vector<HalStreamBuffer> * outBufs)2336 int ExternalCameraDeviceSession::OutputThread::waitForBufferRequestDone(
2337         std::vector<HalStreamBuffer>* outBufs) {
2338     if (mBufferRequestThread == nullptr) {
2339         return 0;
2340     }
2341     return mBufferRequestThread->waitForBufferRequestDone(outBufs);
2342 }
2343 
waitForNextRequest(std::shared_ptr<HalRequest> * out)2344 void ExternalCameraDeviceSession::OutputThread::waitForNextRequest(
2345         std::shared_ptr<HalRequest>* out) {
2346     ATRACE_CALL();
2347     if (out == nullptr) {
2348         ALOGE("%s: out is null", __FUNCTION__);
2349         return;
2350     }
2351 
2352     std::unique_lock<std::mutex> lk(mRequestListLock);
2353     int waitTimes = 0;
2354     while (mRequestList.empty()) {
2355         if (exitPending()) {
2356             return;
2357         }
2358         auto timeout = std::chrono::milliseconds(kReqWaitTimeoutMs);
2359         auto st = mRequestCond.wait_for(lk, timeout);
2360         if (st == std::cv_status::timeout) {
2361             waitTimes++;
2362             if (waitTimes == kReqWaitTimesMax) {
2363                 // no new request, return
2364                 return;
2365             }
2366         }
2367     }
2368     *out = mRequestList.front();
2369     mRequestList.pop_front();
2370     mProcessingRequest = true;
2371     mProcessingFrameNumber = (*out)->frameNumber;
2372 }
2373 
signalRequestDone()2374 void ExternalCameraDeviceSession::OutputThread::signalRequestDone() {
2375     std::unique_lock<std::mutex> lk(mRequestListLock);
2376     mProcessingRequest = false;
2377     mProcessingFrameNumber = 0;
2378     lk.unlock();
2379     mRequestDoneCond.notify_one();
2380 }
2381 
cropAndScaleLocked(std::shared_ptr<AllocatedFrame> & in,const Size & outSz,YCbCrLayout * out)2382 int ExternalCameraDeviceSession::OutputThread::cropAndScaleLocked(
2383         std::shared_ptr<AllocatedFrame>& in, const Size& outSz, YCbCrLayout* out) {
2384     Size inSz = {in->mWidth, in->mHeight};
2385 
2386     int ret;
2387     if (inSz == outSz) {
2388         ret = in->getLayout(out);
2389         if (ret != 0) {
2390             ALOGE("%s: failed to get input image layout", __FUNCTION__);
2391             return ret;
2392         }
2393         return ret;
2394     }
2395 
2396     // Cropping to output aspect ratio
2397     IMapper::Rect inputCrop;
2398     ret = getCropRect(mCroppingType, inSz, outSz, &inputCrop);
2399     if (ret != 0) {
2400         ALOGE("%s: failed to compute crop rect for output size %dx%d", __FUNCTION__, outSz.width,
2401               outSz.height);
2402         return ret;
2403     }
2404 
2405     YCbCrLayout croppedLayout;
2406     ret = in->getCroppedLayout(inputCrop, &croppedLayout);
2407     if (ret != 0) {
2408         ALOGE("%s: failed to crop input image %dx%d to output size %dx%d", __FUNCTION__, inSz.width,
2409               inSz.height, outSz.width, outSz.height);
2410         return ret;
2411     }
2412 
2413     if ((mCroppingType == VERTICAL && inSz.width == outSz.width) ||
2414         (mCroppingType == HORIZONTAL && inSz.height == outSz.height)) {
2415         // No scale is needed
2416         *out = croppedLayout;
2417         return 0;
2418     }
2419 
2420     auto it = mScaledYu12Frames.find(outSz);
2421     std::shared_ptr<AllocatedFrame> scaledYu12Buf;
2422     if (it != mScaledYu12Frames.end()) {
2423         scaledYu12Buf = it->second;
2424     } else {
2425         it = mIntermediateBuffers.find(outSz);
2426         if (it == mIntermediateBuffers.end()) {
2427             ALOGE("%s: failed to find intermediate buffer size %dx%d", __FUNCTION__, outSz.width,
2428                   outSz.height);
2429             return -1;
2430         }
2431         scaledYu12Buf = it->second;
2432     }
2433     // Scale
2434     YCbCrLayout outLayout;
2435     ret = scaledYu12Buf->getLayout(&outLayout);
2436     if (ret != 0) {
2437         ALOGE("%s: failed to get output buffer layout", __FUNCTION__);
2438         return ret;
2439     }
2440 
2441     ret = libyuv::I420Scale(
2442             static_cast<uint8_t*>(croppedLayout.y), croppedLayout.yStride,
2443             static_cast<uint8_t*>(croppedLayout.cb), croppedLayout.cStride,
2444             static_cast<uint8_t*>(croppedLayout.cr), croppedLayout.cStride, inputCrop.width,
2445             inputCrop.height, static_cast<uint8_t*>(outLayout.y), outLayout.yStride,
2446             static_cast<uint8_t*>(outLayout.cb), outLayout.cStride,
2447             static_cast<uint8_t*>(outLayout.cr), outLayout.cStride, outSz.width, outSz.height,
2448             // TODO: b/72261744 see if we can use better filter without losing too much perf
2449             libyuv::FilterMode::kFilterNone);
2450 
2451     if (ret != 0) {
2452         ALOGE("%s: failed to scale buffer from %dx%d to %dx%d. Ret %d", __FUNCTION__,
2453               inputCrop.width, inputCrop.height, outSz.width, outSz.height, ret);
2454         return ret;
2455     }
2456 
2457     *out = outLayout;
2458     mScaledYu12Frames.insert({outSz, scaledYu12Buf});
2459     return 0;
2460 }
2461 
cropAndScaleThumbLocked(std::shared_ptr<AllocatedFrame> & in,const Size & outSz,YCbCrLayout * out)2462 int ExternalCameraDeviceSession::OutputThread::cropAndScaleThumbLocked(
2463         std::shared_ptr<AllocatedFrame>& in, const Size& outSz, YCbCrLayout* out) {
2464     Size inSz{in->mWidth, in->mHeight};
2465 
2466     if ((outSz.width * outSz.height) > (mYu12ThumbFrame->mWidth * mYu12ThumbFrame->mHeight)) {
2467         ALOGE("%s: Requested thumbnail size too big (%d,%d) > (%d,%d)", __FUNCTION__, outSz.width,
2468               outSz.height, mYu12ThumbFrame->mWidth, mYu12ThumbFrame->mHeight);
2469         return -1;
2470     }
2471 
2472     int ret;
2473 
2474     /* This will crop-and-zoom the input YUV frame to the thumbnail size
2475      * Based on the following logic:
2476      *  1) Square pixels come in, square pixels come out, therefore single
2477      *  scale factor is computed to either make input bigger or smaller
2478      *  depending on if we are upscaling or downscaling
2479      *  2) That single scale factor would either make height too tall or width
2480      *  too wide so we need to crop the input either horizontally or vertically
2481      *  but not both
2482      */
2483 
2484     /* Convert the input and output dimensions into floats for ease of math */
2485     float fWin = static_cast<float>(inSz.width);
2486     float fHin = static_cast<float>(inSz.height);
2487     float fWout = static_cast<float>(outSz.width);
2488     float fHout = static_cast<float>(outSz.height);
2489 
2490     /* Compute the one scale factor from (1) above, it will be the smaller of
2491      * the two possibilities. */
2492     float scaleFactor = std::min(fHin / fHout, fWin / fWout);
2493 
2494     /* Since we are crop-and-zooming (as opposed to letter/pillar boxing) we can
2495      * simply multiply the output by our scaleFactor to get the cropped input
2496      * size. Note that at least one of {fWcrop, fHcrop} is going to wind up
2497      * being {fWin, fHin} respectively because fHout or fWout cancels out the
2498      * scaleFactor calculation above.
2499      *
2500      * Specifically:
2501      *  if ( fHin / fHout ) < ( fWin / fWout ) we crop the sides off
2502      * input, in which case
2503      *    scaleFactor = fHin / fHout
2504      *    fWcrop = fHin / fHout * fWout
2505      *    fHcrop = fHin
2506      *
2507      * Note that fWcrop <= fWin ( because ( fHin / fHout ) * fWout < fWin, which
2508      * is just the inequality above with both sides multiplied by fWout
2509      *
2510      * on the other hand if ( fWin / fWout ) < ( fHin / fHout) we crop the top
2511      * and the bottom off of input, and
2512      *    scaleFactor = fWin / fWout
2513      *    fWcrop = fWin
2514      *    fHCrop = fWin / fWout * fHout
2515      */
2516     float fWcrop = scaleFactor * fWout;
2517     float fHcrop = scaleFactor * fHout;
2518 
2519     /* Convert to integer and truncate to an even number */
2520     Size cropSz = {.width = 2 * static_cast<int32_t>(fWcrop / 2.0f),
2521                    .height = 2 * static_cast<int32_t>(fHcrop / 2.0f)};
2522 
2523     /* Convert to a centered rectange with even top/left */
2524     IMapper::Rect inputCrop{.left = 2 * static_cast<int32_t>((inSz.width - cropSz.width) / 4),
2525                             .top = 2 * static_cast<int32_t>((inSz.height - cropSz.height) / 4),
2526                             .width = static_cast<int32_t>(cropSz.width),
2527                             .height = static_cast<int32_t>(cropSz.height)};
2528 
2529     if ((inputCrop.top < 0) || (inputCrop.top >= static_cast<int32_t>(inSz.height)) ||
2530         (inputCrop.left < 0) || (inputCrop.left >= static_cast<int32_t>(inSz.width)) ||
2531         (inputCrop.width <= 0) ||
2532         (inputCrop.width + inputCrop.left > static_cast<int32_t>(inSz.width)) ||
2533         (inputCrop.height <= 0) ||
2534         (inputCrop.height + inputCrop.top > static_cast<int32_t>(inSz.height))) {
2535         ALOGE("%s: came up with really wrong crop rectangle", __FUNCTION__);
2536         ALOGE("%s: input layout %dx%d to for output size %dx%d", __FUNCTION__, inSz.width,
2537               inSz.height, outSz.width, outSz.height);
2538         ALOGE("%s: computed input crop +%d,+%d %dx%d", __FUNCTION__, inputCrop.left, inputCrop.top,
2539               inputCrop.width, inputCrop.height);
2540         return -1;
2541     }
2542 
2543     YCbCrLayout inputLayout;
2544     ret = in->getCroppedLayout(inputCrop, &inputLayout);
2545     if (ret != 0) {
2546         ALOGE("%s: failed to crop input layout %dx%d to for output size %dx%d", __FUNCTION__,
2547               inSz.width, inSz.height, outSz.width, outSz.height);
2548         ALOGE("%s: computed input crop +%d,+%d %dx%d", __FUNCTION__, inputCrop.left, inputCrop.top,
2549               inputCrop.width, inputCrop.height);
2550         return ret;
2551     }
2552     ALOGV("%s: crop input layout %dx%d to for output size %dx%d", __FUNCTION__, inSz.width,
2553           inSz.height, outSz.width, outSz.height);
2554     ALOGV("%s: computed input crop +%d,+%d %dx%d", __FUNCTION__, inputCrop.left, inputCrop.top,
2555           inputCrop.width, inputCrop.height);
2556 
2557     // Scale
2558     YCbCrLayout outFullLayout;
2559 
2560     ret = mYu12ThumbFrame->getLayout(&outFullLayout);
2561     if (ret != 0) {
2562         ALOGE("%s: failed to get output buffer layout", __FUNCTION__);
2563         return ret;
2564     }
2565 
2566     ret = libyuv::I420Scale(static_cast<uint8_t*>(inputLayout.y), inputLayout.yStride,
2567                             static_cast<uint8_t*>(inputLayout.cb), inputLayout.cStride,
2568                             static_cast<uint8_t*>(inputLayout.cr), inputLayout.cStride,
2569                             inputCrop.width, inputCrop.height,
2570                             static_cast<uint8_t*>(outFullLayout.y), outFullLayout.yStride,
2571                             static_cast<uint8_t*>(outFullLayout.cb), outFullLayout.cStride,
2572                             static_cast<uint8_t*>(outFullLayout.cr), outFullLayout.cStride,
2573                             outSz.width, outSz.height, libyuv::FilterMode::kFilterNone);
2574 
2575     if (ret != 0) {
2576         ALOGE("%s: failed to scale buffer from %dx%d to %dx%d. Ret %d", __FUNCTION__,
2577               inputCrop.width, inputCrop.height, outSz.width, outSz.height, ret);
2578         return ret;
2579     }
2580 
2581     *out = outFullLayout;
2582     return 0;
2583 }
2584 
createJpegLocked(HalStreamBuffer & halBuf,const common::V1_0::helper::CameraMetadata & setting)2585 int ExternalCameraDeviceSession::OutputThread::createJpegLocked(
2586         HalStreamBuffer& halBuf, const common::V1_0::helper::CameraMetadata& setting) {
2587     ATRACE_CALL();
2588     int ret;
2589     auto lfail = [&](auto... args) {
2590         ALOGE(args...);
2591 
2592         return 1;
2593     };
2594     auto parent = mParent.lock();
2595     if (parent == nullptr) {
2596         ALOGE("%s: session has been disconnected!", __FUNCTION__);
2597         return 1;
2598     }
2599 
2600     ALOGV("%s: HAL buffer sid: %d bid: %" PRIu64 " w: %u h: %u", __FUNCTION__, halBuf.streamId,
2601           static_cast<uint64_t>(halBuf.bufferId), halBuf.width, halBuf.height);
2602     ALOGV("%s: HAL buffer fmt: %x usage: %" PRIx64 " ptr: %p", __FUNCTION__, halBuf.format,
2603           static_cast<uint64_t>(halBuf.usage), halBuf.bufPtr);
2604     ALOGV("%s: YV12 buffer %d x %d", __FUNCTION__, mYu12Frame->mWidth, mYu12Frame->mHeight);
2605 
2606     int jpegQuality, thumbQuality;
2607     Size thumbSize;
2608     bool outputThumbnail = true;
2609 
2610     if (setting.exists(ANDROID_JPEG_QUALITY)) {
2611         camera_metadata_ro_entry entry = setting.find(ANDROID_JPEG_QUALITY);
2612         jpegQuality = entry.data.u8[0];
2613     } else {
2614         return lfail("%s: ANDROID_JPEG_QUALITY not set", __FUNCTION__);
2615     }
2616 
2617     if (setting.exists(ANDROID_JPEG_THUMBNAIL_QUALITY)) {
2618         camera_metadata_ro_entry entry = setting.find(ANDROID_JPEG_THUMBNAIL_QUALITY);
2619         thumbQuality = entry.data.u8[0];
2620     } else {
2621         return lfail("%s: ANDROID_JPEG_THUMBNAIL_QUALITY not set", __FUNCTION__);
2622     }
2623 
2624     if (setting.exists(ANDROID_JPEG_THUMBNAIL_SIZE)) {
2625         camera_metadata_ro_entry entry = setting.find(ANDROID_JPEG_THUMBNAIL_SIZE);
2626         thumbSize = Size{.width = entry.data.i32[0], .height = entry.data.i32[1]};
2627         if (thumbSize.width == 0 && thumbSize.height == 0) {
2628             outputThumbnail = false;
2629         }
2630     } else {
2631         return lfail("%s: ANDROID_JPEG_THUMBNAIL_SIZE not set", __FUNCTION__);
2632     }
2633 
2634     /* Cropped and scaled YU12 buffer for main and thumbnail */
2635     YCbCrLayout yu12Main;
2636     Size jpegSize{halBuf.width, halBuf.height};
2637 
2638     /* Compute temporary buffer sizes accounting for the following:
2639      * thumbnail can't exceed APP1 size of 64K
2640      * main image needs to hold APP1, headers, and at most a poorly
2641      * compressed image */
2642     const ssize_t maxThumbCodeSize = 64 * 1024;
2643     const ssize_t maxJpegCodeSize =
2644             mBlobBufferSize == 0 ? parent->getJpegBufferSize(jpegSize.width, jpegSize.height)
2645                                  : mBlobBufferSize;
2646 
2647     /* Check that getJpegBufferSize did not return an error */
2648     if (maxJpegCodeSize < 0) {
2649         return lfail("%s: getJpegBufferSize returned %zd", __FUNCTION__, maxJpegCodeSize);
2650     }
2651 
2652     /* Hold actual thumbnail and main image code sizes */
2653     size_t thumbCodeSize = 0, jpegCodeSize = 0;
2654     /* Temporary thumbnail code buffer */
2655     std::vector<uint8_t> thumbCode(outputThumbnail ? maxThumbCodeSize : 0);
2656 
2657     YCbCrLayout yu12Thumb;
2658     if (outputThumbnail) {
2659         ret = cropAndScaleThumbLocked(mYu12Frame, thumbSize, &yu12Thumb);
2660 
2661         if (ret != 0) {
2662             return lfail("%s: crop and scale thumbnail failed!", __FUNCTION__);
2663         }
2664     }
2665 
2666     /* Scale and crop main jpeg */
2667     ret = cropAndScaleLocked(mYu12Frame, jpegSize, &yu12Main);
2668 
2669     if (ret != 0) {
2670         return lfail("%s: crop and scale main failed!", __FUNCTION__);
2671     }
2672 
2673     /* Encode the thumbnail image */
2674     if (outputThumbnail) {
2675         ret = encodeJpegYU12(thumbSize, yu12Thumb, thumbQuality, 0, 0, &thumbCode[0],
2676                              maxThumbCodeSize, thumbCodeSize);
2677 
2678         if (ret != 0) {
2679             return lfail("%s: thumbnail encodeJpegYU12 failed with %d", __FUNCTION__, ret);
2680         }
2681     }
2682 
2683     /* Combine camera characteristics with request settings to form EXIF
2684      * metadata */
2685     common::V1_0::helper::CameraMetadata meta(mCameraCharacteristics);
2686     meta.append(setting);
2687 
2688     /* Generate EXIF object */
2689     std::unique_ptr<ExifUtils> utils(ExifUtils::create());
2690     /* Make sure it's initialized */
2691     utils->initialize();
2692 
2693     utils->setFromMetadata(meta, jpegSize.width, jpegSize.height);
2694     utils->setMake(mExifMake);
2695     utils->setModel(mExifModel);
2696 
2697     ret = utils->generateApp1(outputThumbnail ? &thumbCode[0] : nullptr, thumbCodeSize);
2698 
2699     if (!ret) {
2700         return lfail("%s: generating APP1 failed", __FUNCTION__);
2701     }
2702 
2703     /* Get internal buffer */
2704     size_t exifDataSize = utils->getApp1Length();
2705     const uint8_t* exifData = utils->getApp1Buffer();
2706 
2707     /* Lock the HAL jpeg code buffer */
2708     void* bufPtr = sHandleImporter.lock(*(halBuf.bufPtr), static_cast<uint64_t>(halBuf.usage),
2709                                         maxJpegCodeSize);
2710 
2711     if (!bufPtr) {
2712         return lfail("%s: could not lock %zu bytes", __FUNCTION__, maxJpegCodeSize);
2713     }
2714 
2715     /* Encode the main jpeg image */
2716     ret = encodeJpegYU12(jpegSize, yu12Main, jpegQuality, exifData, exifDataSize, bufPtr,
2717                          maxJpegCodeSize, jpegCodeSize);
2718 
2719     /* TODO: Not sure this belongs here, maybe better to pass jpegCodeSize out
2720      * and do this when returning buffer to parent */
2721     CameraBlob blob{CameraBlobId::JPEG, static_cast<int32_t>(jpegCodeSize)};
2722     void* blobDst = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(bufPtr) + maxJpegCodeSize -
2723                                             sizeof(CameraBlob));
2724     memcpy(blobDst, &blob, sizeof(CameraBlob));
2725 
2726     /* Unlock the HAL jpeg code buffer */
2727     int relFence = sHandleImporter.unlock(*(halBuf.bufPtr));
2728     if (relFence >= 0) {
2729         halBuf.acquireFence = relFence;
2730     }
2731 
2732     /* Check if our JPEG actually succeeded */
2733     if (ret != 0) {
2734         return lfail("%s: encodeJpegYU12 failed with %d", __FUNCTION__, ret);
2735     }
2736 
2737     ALOGV("%s: encoded JPEG (ret:%d) with Q:%d max size: %zu", __FUNCTION__, ret, jpegQuality,
2738           maxJpegCodeSize);
2739 
2740     return 0;
2741 }
2742 
clearIntermediateBuffers()2743 void ExternalCameraDeviceSession::OutputThread::clearIntermediateBuffers() {
2744     std::lock_guard<std::mutex> lk(mBufferLock);
2745     mYu12Frame.reset();
2746     mYu12ThumbFrame.reset();
2747     mIntermediateBuffers.clear();
2748     mMuteTestPatternFrame.clear();
2749     mBlobBufferSize = 0;
2750 }
2751 
threadLoop()2752 bool ExternalCameraDeviceSession::OutputThread::threadLoop() {
2753     std::shared_ptr<HalRequest> req;
2754     auto parent = mParent.lock();
2755     if (parent == nullptr) {
2756         ALOGE("%s: session has been disconnected!", __FUNCTION__);
2757         return false;
2758     }
2759 
2760     // TODO: maybe we need to setup a sensor thread to dq/enq v4l frames
2761     //       regularly to prevent v4l buffer queue filled with stale buffers
2762     //       when app doesn't program a preview request
2763     waitForNextRequest(&req);
2764     if (req == nullptr) {
2765         // No new request, wait again
2766         return true;
2767     }
2768 
2769     auto onDeviceError = [&](auto... args) {
2770         ALOGE(args...);
2771         parent->notifyError(req->frameNumber, /*stream*/ -1, ErrorCode::ERROR_DEVICE);
2772         signalRequestDone();
2773         return false;
2774     };
2775 
2776     if (req->frameIn->mFourcc != V4L2_PIX_FMT_MJPEG && req->frameIn->mFourcc != V4L2_PIX_FMT_Z16) {
2777         return onDeviceError("%s: do not support V4L2 format %c%c%c%c", __FUNCTION__,
2778                              req->frameIn->mFourcc & 0xFF, (req->frameIn->mFourcc >> 8) & 0xFF,
2779                              (req->frameIn->mFourcc >> 16) & 0xFF,
2780                              (req->frameIn->mFourcc >> 24) & 0xFF);
2781     }
2782 
2783     int res = requestBufferStart(req->buffers);
2784     if (res != 0) {
2785         ALOGE("%s: send BufferRequest failed! res %d", __FUNCTION__, res);
2786         return onDeviceError("%s: failed to send buffer request!", __FUNCTION__);
2787     }
2788 
2789     std::unique_lock<std::mutex> lk(mBufferLock);
2790     // Convert input V4L2 frame to YU12 of the same size
2791     // TODO: see if we can save some computation by converting to YV12 here
2792     uint8_t* inData;
2793     size_t inDataSize;
2794     if (req->frameIn->getData(&inData, &inDataSize) != 0) {
2795         lk.unlock();
2796         return onDeviceError("%s: V4L2 buffer map failed", __FUNCTION__);
2797     }
2798 
2799     // Process camera mute state
2800     auto testPatternMode = req->setting.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2801     if (testPatternMode.count == 1) {
2802         if (mCameraMuted != (testPatternMode.data.u8[0] != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF)) {
2803             mCameraMuted = !mCameraMuted;
2804             // Get solid color for test pattern, if any was set
2805             if (testPatternMode.data.u8[0] == ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
2806                 auto entry = req->setting.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2807                 if (entry.count == 4) {
2808                     // Update the mute frame if the pattern color has changed
2809                     if (memcmp(entry.data.i32, mTestPatternData, sizeof(mTestPatternData)) != 0) {
2810                         memcpy(mTestPatternData, entry.data.i32, sizeof(mTestPatternData));
2811                         // Fill the mute frame with the solid color, use only 8 MSB of RGGB as RGB
2812                         for (int i = 0; i < mMuteTestPatternFrame.size(); i += 3) {
2813                             mMuteTestPatternFrame[i] = entry.data.i32[0] >> 24;
2814                             mMuteTestPatternFrame[i + 1] = entry.data.i32[1] >> 24;
2815                             mMuteTestPatternFrame[i + 2] = entry.data.i32[3] >> 24;
2816                         }
2817                     }
2818                 }
2819             }
2820         }
2821     }
2822 
2823     // TODO: in some special case maybe we can decode jpg directly to gralloc output?
2824     if (req->frameIn->mFourcc == V4L2_PIX_FMT_MJPEG) {
2825         ATRACE_BEGIN("MJPGtoI420");
2826         res = 0;
2827         if (mCameraMuted) {
2828             res = libyuv::ConvertToI420(
2829                     mMuteTestPatternFrame.data(), mMuteTestPatternFrame.size(),
2830                     static_cast<uint8_t*>(mYu12FrameLayout.y), mYu12FrameLayout.yStride,
2831                     static_cast<uint8_t*>(mYu12FrameLayout.cb), mYu12FrameLayout.cStride,
2832                     static_cast<uint8_t*>(mYu12FrameLayout.cr), mYu12FrameLayout.cStride, 0, 0,
2833                     mYu12Frame->mWidth, mYu12Frame->mHeight, mYu12Frame->mWidth,
2834                     mYu12Frame->mHeight, libyuv::kRotate0, libyuv::FOURCC_RAW);
2835         } else {
2836             res = libyuv::MJPGToI420(
2837                     inData, inDataSize, static_cast<uint8_t*>(mYu12FrameLayout.y),
2838                     mYu12FrameLayout.yStride, static_cast<uint8_t*>(mYu12FrameLayout.cb),
2839                     mYu12FrameLayout.cStride, static_cast<uint8_t*>(mYu12FrameLayout.cr),
2840                     mYu12FrameLayout.cStride, mYu12Frame->mWidth, mYu12Frame->mHeight,
2841                     mYu12Frame->mWidth, mYu12Frame->mHeight);
2842         }
2843         ATRACE_END();
2844 
2845         if (res != 0) {
2846             // For some webcam, the first few V4L2 frames might be malformed...
2847             ALOGE("%s: Convert V4L2 frame to YU12 failed! res %d", __FUNCTION__, res);
2848 
2849             ATRACE_BEGIN("Wait for BufferRequest done");
2850             res = waitForBufferRequestDone(&req->buffers);
2851             ATRACE_END();
2852 
2853             lk.unlock();
2854             Status st = parent->processCaptureRequestError(req);
2855             if (st != Status::OK) {
2856                 return onDeviceError("%s: failed to process capture request error!", __FUNCTION__);
2857             }
2858             signalRequestDone();
2859             return true;
2860         }
2861     }
2862 
2863     ATRACE_BEGIN("Wait for BufferRequest done");
2864     res = waitForBufferRequestDone(&req->buffers);
2865     ATRACE_END();
2866 
2867     if (res != 0) {
2868         // HAL buffer management buffer request can fail
2869         ALOGE("%s: wait for BufferRequest done failed! res %d", __FUNCTION__, res);
2870         lk.unlock();
2871         Status st = parent->processCaptureRequestError(req);
2872         if (st != Status::OK) {
2873             return onDeviceError("%s: failed to process capture request error!", __FUNCTION__);
2874         }
2875         signalRequestDone();
2876         return true;
2877     }
2878 
2879     ALOGV("%s processing new request", __FUNCTION__);
2880     const int kSyncWaitTimeoutMs = 500;
2881     for (auto& halBuf : req->buffers) {
2882         if (*(halBuf.bufPtr) == nullptr) {
2883             ALOGW("%s: buffer for stream %d missing", __FUNCTION__, halBuf.streamId);
2884             halBuf.fenceTimeout = true;
2885         } else if (halBuf.acquireFence >= 0) {
2886             int ret = sync_wait(halBuf.acquireFence, kSyncWaitTimeoutMs);
2887             if (ret) {
2888                 halBuf.fenceTimeout = true;
2889             } else {
2890                 ::close(halBuf.acquireFence);
2891                 halBuf.acquireFence = -1;
2892             }
2893         }
2894 
2895         if (halBuf.fenceTimeout) {
2896             continue;
2897         }
2898 
2899         // Gralloc lockYCbCr the buffer
2900         switch (halBuf.format) {
2901             case PixelFormat::BLOB: {
2902                 int ret = createJpegLocked(halBuf, req->setting);
2903 
2904                 if (ret != 0) {
2905                     lk.unlock();
2906                     return onDeviceError("%s: createJpegLocked failed with %d", __FUNCTION__, ret);
2907                 }
2908             } break;
2909             case PixelFormat::Y16: {
2910                 void* outLayout = sHandleImporter.lock(
2911                         *(halBuf.bufPtr), static_cast<uint64_t>(halBuf.usage), inDataSize);
2912 
2913                 std::memcpy(outLayout, inData, inDataSize);
2914 
2915                 int relFence = sHandleImporter.unlock(*(halBuf.bufPtr));
2916                 if (relFence >= 0) {
2917                     halBuf.acquireFence = relFence;
2918                 }
2919             } break;
2920             case PixelFormat::YCBCR_420_888:
2921             case PixelFormat::YV12: {
2922                 android::Rect outRect{0, 0, static_cast<int32_t>(halBuf.width),
2923                                       static_cast<int32_t>(halBuf.height)};
2924                 android_ycbcr result = sHandleImporter.lockYCbCr(
2925                         *(halBuf.bufPtr), static_cast<uint64_t>(halBuf.usage), outRect);
2926                 ALOGV("%s: outLayout y %p cb %p cr %p y_str %zu c_str %zu c_step %zu", __FUNCTION__,
2927                       result.y, result.cb, result.cr, result.ystride, result.cstride,
2928                       result.chroma_step);
2929                 if (result.ystride > UINT32_MAX || result.cstride > UINT32_MAX ||
2930                     result.chroma_step > UINT32_MAX) {
2931                     return onDeviceError("%s: lockYCbCr failed. Unexpected values!", __FUNCTION__);
2932                 }
2933                 YCbCrLayout outLayout = {.y = result.y,
2934                                          .cb = result.cb,
2935                                          .cr = result.cr,
2936                                          .yStride = static_cast<uint32_t>(result.ystride),
2937                                          .cStride = static_cast<uint32_t>(result.cstride),
2938                                          .chromaStep = static_cast<uint32_t>(result.chroma_step)};
2939 
2940                 // Convert to output buffer size/format
2941                 uint32_t outputFourcc = getFourCcFromLayout(outLayout);
2942                 ALOGV("%s: converting to format %c%c%c%c", __FUNCTION__, outputFourcc & 0xFF,
2943                       (outputFourcc >> 8) & 0xFF, (outputFourcc >> 16) & 0xFF,
2944                       (outputFourcc >> 24) & 0xFF);
2945 
2946                 YCbCrLayout cropAndScaled;
2947                 ATRACE_BEGIN("cropAndScaleLocked");
2948                 int ret = cropAndScaleLocked(mYu12Frame, Size{halBuf.width, halBuf.height},
2949                                              &cropAndScaled);
2950                 ATRACE_END();
2951                 if (ret != 0) {
2952                     lk.unlock();
2953                     return onDeviceError("%s: crop and scale failed!", __FUNCTION__);
2954                 }
2955 
2956                 Size sz{halBuf.width, halBuf.height};
2957                 ATRACE_BEGIN("formatConvert");
2958                 ret = formatConvert(cropAndScaled, outLayout, sz, outputFourcc);
2959                 ATRACE_END();
2960                 if (ret != 0) {
2961                     lk.unlock();
2962                     return onDeviceError("%s: format conversion failed!", __FUNCTION__);
2963                 }
2964                 int relFence = sHandleImporter.unlock(*(halBuf.bufPtr));
2965                 if (relFence >= 0) {
2966                     halBuf.acquireFence = relFence;
2967                 }
2968             } break;
2969             default:
2970                 lk.unlock();
2971                 return onDeviceError("%s: unknown output format %x", __FUNCTION__, halBuf.format);
2972         }
2973     }  // for each buffer
2974     mScaledYu12Frames.clear();
2975 
2976     // Don't hold the lock while calling back to parent
2977     lk.unlock();
2978     Status st = parent->processCaptureResult(req);
2979     if (st != Status::OK) {
2980         return onDeviceError("%s: failed to process capture result!", __FUNCTION__);
2981     }
2982     signalRequestDone();
2983     return true;
2984 }
2985 
2986 // End ExternalCameraDeviceSession::OutputThread functions
2987 
2988 }  // namespace implementation
2989 }  // namespace device
2990 }  // namespace camera
2991 }  // namespace hardware
2992 }  // namespace android
2993