1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef ANDROID_HARDWARE_CAMERA_DEVICE_V3_4_EXTCAMERADEVICESESSION_H
18 #define ANDROID_HARDWARE_CAMERA_DEVICE_V3_4_EXTCAMERADEVICESESSION_H
19 
20 #include <android/hardware/camera/device/3.2/ICameraDevice.h>
21 #include <android/hardware/camera/device/3.4/ICameraDeviceSession.h>
22 #include <fmq/MessageQueue.h>
23 #include <hidl/MQDescriptor.h>
24 #include <hidl/Status.h>
25 #include <include/convert.h>
26 #include <chrono>
27 #include <condition_variable>
28 #include <list>
29 #include <unordered_map>
30 #include <unordered_set>
31 #include "CameraMetadata.h"
32 #include "HandleImporter.h"
33 #include "Exif.h"
34 #include "utils/KeyedVector.h"
35 #include "utils/Mutex.h"
36 #include "utils/Thread.h"
37 #include "android-base/unique_fd.h"
38 #include "ExternalCameraUtils.h"
39 
40 namespace android {
41 namespace hardware {
42 namespace camera {
43 namespace device {
44 namespace V3_4 {
45 namespace implementation {
46 
47 using ::android::hardware::camera::device::V3_2::BufferCache;
48 using ::android::hardware::camera::device::V3_2::BufferStatus;
49 using ::android::hardware::camera::device::V3_2::CameraMetadata;
50 using ::android::hardware::camera::device::V3_2::CaptureRequest;
51 using ::android::hardware::camera::device::V3_2::CaptureResult;
52 using ::android::hardware::camera::device::V3_2::ErrorCode;
53 using ::android::hardware::camera::device::V3_2::ICameraDeviceCallback;
54 using ::android::hardware::camera::device::V3_2::MsgType;
55 using ::android::hardware::camera::device::V3_2::NotifyMsg;
56 using ::android::hardware::camera::device::V3_2::RequestTemplate;
57 using ::android::hardware::camera::device::V3_2::Stream;
58 using ::android::hardware::camera::device::V3_4::StreamConfiguration;
59 using ::android::hardware::camera::device::V3_2::StreamConfigurationMode;
60 using ::android::hardware::camera::device::V3_2::StreamRotation;
61 using ::android::hardware::camera::device::V3_2::StreamType;
62 using ::android::hardware::camera::device::V3_2::DataspaceFlags;
63 using ::android::hardware::camera::device::V3_2::CameraBlob;
64 using ::android::hardware::camera::device::V3_2::CameraBlobId;
65 using ::android::hardware::camera::device::V3_4::HalStreamConfiguration;
66 using ::android::hardware::camera::device::V3_4::ICameraDeviceSession;
67 using ::android::hardware::camera::common::V1_0::Status;
68 using ::android::hardware::camera::common::V1_0::helper::HandleImporter;
69 using ::android::hardware::camera::common::V1_0::helper::ExifUtils;
70 using ::android::hardware::camera::external::common::ExternalCameraConfig;
71 using ::android::hardware::camera::external::common::Size;
72 using ::android::hardware::camera::external::common::SizeHasher;
73 using ::android::hardware::graphics::common::V1_0::BufferUsage;
74 using ::android::hardware::graphics::common::V1_0::Dataspace;
75 using ::android::hardware::graphics::common::V1_0::PixelFormat;
76 using ::android::hardware::kSynchronizedReadWrite;
77 using ::android::hardware::MessageQueue;
78 using ::android::hardware::MQDescriptorSync;
79 using ::android::hardware::Return;
80 using ::android::hardware::Void;
81 using ::android::hardware::hidl_vec;
82 using ::android::hardware::hidl_string;
83 using ::android::sp;
84 using ::android::Mutex;
85 using ::android::base::unique_fd;
86 
87 struct ExternalCameraDeviceSession : public virtual RefBase,
88         public virtual OutputThreadInterface {
89 
90     ExternalCameraDeviceSession(const sp<ICameraDeviceCallback>&,
91             const ExternalCameraConfig& cfg,
92             const std::vector<SupportedV4L2Format>& sortedFormats,
93             const CroppingType& croppingType,
94             const common::V1_0::helper::CameraMetadata& chars,
95             const std::string& cameraId,
96             unique_fd v4l2Fd);
97     virtual ~ExternalCameraDeviceSession();
98     // Call by CameraDevice to dump active device states
99     void dumpState(const native_handle_t*);
100     // Caller must use this method to check if CameraDeviceSession ctor failed
101     bool isInitFailed();
102     bool isClosed();
103 
104     // Retrieve the HIDL interface, split into its own class to avoid inheritance issues when
105     // dealing with minor version revs and simultaneous implementation and interface inheritance
getInterfaceExternalCameraDeviceSession106     virtual sp<ICameraDeviceSession> getInterface() {
107         return new TrampolineSessionInterface_3_4(this);
108     }
109 
110     static const int kMaxProcessedStream = 2;
111     static const int kMaxStallStream = 1;
112     static const uint32_t kMaxBytesPerPixel = 2;
113 
114     class OutputThread : public android::Thread {
115     public:
116         OutputThread(wp<OutputThreadInterface> parent, CroppingType,
117                 const common::V1_0::helper::CameraMetadata&);
118         virtual ~OutputThread();
119 
120         Status allocateIntermediateBuffers(
121                 const Size& v4lSize, const Size& thumbSize,
122                 const hidl_vec<Stream>& streams,
123                 uint32_t blobBufferSize);
124         Status submitRequest(const std::shared_ptr<HalRequest>&);
125         void flush();
126         void dump(int fd);
127         virtual bool threadLoop() override;
128 
129         void setExifMakeModel(const std::string& make, const std::string& model);
130 
131         // The remaining request list is returned for offline processing
132         std::list<std::shared_ptr<HalRequest>> switchToOffline();
133 
134     protected:
135         // Methods to request output buffer in parallel
136         // No-op for device@3.4. Implemented in device@3.5
requestBufferStartExternalCameraDeviceSession137         virtual int requestBufferStart(const std::vector<HalStreamBuffer>&) { return 0; }
waitForBufferRequestDoneExternalCameraDeviceSession138         virtual int waitForBufferRequestDone(
139                 /*out*/std::vector<HalStreamBuffer>*) { return 0; }
140 
141         static const int kFlushWaitTimeoutSec = 3; // 3 sec
142         static const int kReqWaitTimeoutMs = 33;   // 33ms
143         static const int kReqWaitTimesMax = 90;    // 33ms * 90 ~= 3 sec
144 
145         void waitForNextRequest(std::shared_ptr<HalRequest>* out);
146         void signalRequestDone();
147 
148         int cropAndScaleLocked(
149                 sp<AllocatedFrame>& in, const Size& outSize,
150                 YCbCrLayout* out);
151 
152         int cropAndScaleThumbLocked(
153                 sp<AllocatedFrame>& in, const Size& outSize,
154                 YCbCrLayout* out);
155 
156         int createJpegLocked(HalStreamBuffer &halBuf,
157                 const common::V1_0::helper::CameraMetadata& settings);
158 
159         void clearIntermediateBuffers();
160 
161         const wp<OutputThreadInterface> mParent;
162         const CroppingType mCroppingType;
163         const common::V1_0::helper::CameraMetadata mCameraCharacteristics;
164 
165         mutable std::mutex mRequestListLock;      // Protect acccess to mRequestList,
166                                                   // mProcessingRequest and mProcessingFrameNumer
167         std::condition_variable mRequestCond;     // signaled when a new request is submitted
168         std::condition_variable mRequestDoneCond; // signaled when a request is done processing
169         std::list<std::shared_ptr<HalRequest>> mRequestList;
170         bool mProcessingRequest = false;
171         uint32_t mProcessingFrameNumer = 0;
172 
173         // V4L2 frameIn
174         // (MJPG decode)-> mYu12Frame
175         // (Scale)-> mScaledYu12Frames
176         // (Format convert) -> output gralloc frames
177         mutable std::mutex mBufferLock; // Protect access to intermediate buffers
178         sp<AllocatedFrame> mYu12Frame;
179         sp<AllocatedFrame> mYu12ThumbFrame;
180         std::unordered_map<Size, sp<AllocatedFrame>, SizeHasher> mIntermediateBuffers;
181         std::unordered_map<Size, sp<AllocatedFrame>, SizeHasher> mScaledYu12Frames;
182         YCbCrLayout mYu12FrameLayout;
183         YCbCrLayout mYu12ThumbFrameLayout;
184         uint32_t mBlobBufferSize = 0; // 0 -> HAL derive buffer size, else: use given size
185 
186         std::string mExifMake;
187         std::string mExifModel;
188     };
189 
190 protected:
191 
192     // Methods from ::android::hardware::camera::device::V3_2::ICameraDeviceSession follow
193 
194     Return<void> constructDefaultRequestSettings(
195             RequestTemplate,
196             ICameraDeviceSession::constructDefaultRequestSettings_cb _hidl_cb);
197 
198     Return<void> configureStreams(
199             const V3_2::StreamConfiguration&,
200             ICameraDeviceSession::configureStreams_cb);
201 
202     Return<void> getCaptureRequestMetadataQueue(
203         ICameraDeviceSession::getCaptureRequestMetadataQueue_cb);
204 
205     Return<void> getCaptureResultMetadataQueue(
206         ICameraDeviceSession::getCaptureResultMetadataQueue_cb);
207 
208     Return<void> processCaptureRequest(
209             const hidl_vec<CaptureRequest>&,
210             const hidl_vec<BufferCache>&,
211             ICameraDeviceSession::processCaptureRequest_cb);
212 
213     Return<Status> flush();
214     Return<void> close(bool callerIsDtor = false);
215 
216     Return<void> configureStreams_3_3(
217             const V3_2::StreamConfiguration&,
218             ICameraDeviceSession::configureStreams_3_3_cb);
219 
220     Return<void> configureStreams_3_4(
221             const V3_4::StreamConfiguration& requestedConfiguration,
222             ICameraDeviceSession::configureStreams_3_4_cb _hidl_cb);
223 
224     Return<void> processCaptureRequest_3_4(
225             const hidl_vec<V3_4::CaptureRequest>& requests,
226             const hidl_vec<V3_2::BufferCache>& cachesToRemove,
227             ICameraDeviceSession::processCaptureRequest_3_4_cb _hidl_cb);
228 
229 protected:
230     // Methods from OutputThreadInterface
231     virtual Status importBuffer(int32_t streamId,
232             uint64_t bufId, buffer_handle_t buf,
233             /*out*/buffer_handle_t** outBufPtr,
234             bool allowEmptyBuf) override;
235 
236     virtual Status processCaptureResult(std::shared_ptr<HalRequest>&) override;
237 
238     virtual Status processCaptureRequestError(const std::shared_ptr<HalRequest>&,
239         /*out*/std::vector<NotifyMsg>* msgs = nullptr,
240         /*out*/std::vector<CaptureResult>* results = nullptr) override;
241 
242     virtual ssize_t getJpegBufferSize(uint32_t width, uint32_t height) const override;
243 
244     virtual void notifyError(uint32_t frameNumber, int32_t streamId, ErrorCode ec) override;
245     // End of OutputThreadInterface methods
246 
247     Status constructDefaultRequestSettingsRaw(RequestTemplate type,
248             V3_2::CameraMetadata *outMetadata);
249 
250     bool initialize();
251     // To init/close different version of output thread
252     virtual void initOutputThread();
253     virtual void closeOutputThread();
254     void closeOutputThreadImpl();
255 
256     Status initStatus() const;
257     status_t initDefaultRequests();
258     status_t fillCaptureResult(common::V1_0::helper::CameraMetadata& md, nsecs_t timestamp);
259     Status configureStreams(const V3_2::StreamConfiguration&,
260             V3_3::HalStreamConfiguration* out,
261             // Only filled by configureStreams_3_4, and only one blob stream supported
262             uint32_t blobBufferSize = 0);
263     // fps = 0.0 means default, which is
264     // slowest fps that is at least 30, or fastest fps if 30 is not supported
265     int configureV4l2StreamLocked(const SupportedV4L2Format& fmt, double fps = 0.0);
266     int v4l2StreamOffLocked();
267     int setV4l2FpsLocked(double fps);
268     static Status isStreamCombinationSupported(const V3_2::StreamConfiguration& config,
269             const std::vector<SupportedV4L2Format>& supportedFormats,
270             const ExternalCameraConfig& devCfg);
271 
272     // TODO: change to unique_ptr for better tracking
273     sp<V4L2Frame> dequeueV4l2FrameLocked(/*out*/nsecs_t* shutterTs); // Called with mLock hold
274     void enqueueV4l2Frame(const sp<V4L2Frame>&);
275 
276     // Check if input Stream is one of supported stream setting on this device
277     static bool isSupported(const Stream& stream,
278             const std::vector<SupportedV4L2Format>& supportedFormats,
279             const ExternalCameraConfig& cfg);
280 
281     // Validate and import request's output buffers and acquire fence
282     virtual Status importRequestLocked(
283             const CaptureRequest& request,
284             hidl_vec<buffer_handle_t*>& allBufPtrs,
285             hidl_vec<int>& allFences);
286 
287     Status importRequestLockedImpl(
288             const CaptureRequest& request,
289             hidl_vec<buffer_handle_t*>& allBufPtrs,
290             hidl_vec<int>& allFences,
291             // Optional argument for ICameraDeviceSession@3.5 impl
292             bool allowEmptyBuf = false);
293 
294     Status importBufferLocked(int32_t streamId,
295             uint64_t bufId, buffer_handle_t buf,
296             /*out*/buffer_handle_t** outBufPtr,
297             bool allowEmptyBuf);
298 
299     static void cleanupInflightFences(
300             hidl_vec<int>& allFences, size_t numFences);
301     void cleanupBuffersLocked(int id);
302     void updateBufferCaches(const hidl_vec<BufferCache>& cachesToRemove);
303 
304     Status processOneCaptureRequest(const CaptureRequest& request);
305 
306     void notifyShutter(uint32_t frameNumber, nsecs_t shutterTs);
307     void invokeProcessCaptureResultCallback(
308             hidl_vec<CaptureResult> &results, bool tryWriteFmq);
309 
310     Size getMaxJpegResolution() const;
311     Size getMaxThumbResolution() const;
312 
313     int waitForV4L2BufferReturnLocked(std::unique_lock<std::mutex>& lk);
314 
315     // Protect (most of) HIDL interface methods from synchronized-entering
316     mutable Mutex mInterfaceLock;
317 
318     mutable Mutex mLock; // Protect all private members except otherwise noted
319     const sp<ICameraDeviceCallback> mCallback;
320     const ExternalCameraConfig& mCfg;
321     const common::V1_0::helper::CameraMetadata mCameraCharacteristics;
322     const std::vector<SupportedV4L2Format> mSupportedFormats;
323     const CroppingType mCroppingType;
324     const std::string mCameraId;
325 
326     // Not protected by mLock, this is almost a const.
327     // Setup in constructor, reset in close() after OutputThread is joined
328     unique_fd mV4l2Fd;
329 
330     // device is closed either
331     //    - closed by user
332     //    - init failed
333     //    - camera disconnected
334     bool mClosed = false;
335     bool mInitialized = false;
336     bool mInitFail = false;
337     bool mFirstRequest = false;
338     common::V1_0::helper::CameraMetadata mLatestReqSetting;
339 
340     bool mV4l2Streaming = false;
341     SupportedV4L2Format mV4l2StreamingFmt;
342     double mV4l2StreamingFps = 0.0;
343     size_t mV4L2BufferCount = 0;
344 
345     static const int kBufferWaitTimeoutSec = 3; // TODO: handle long exposure (or not allowing)
346     std::mutex mV4l2BufferLock; // protect the buffer count and condition below
347     std::condition_variable mV4L2BufferReturned;
348     size_t mNumDequeuedV4l2Buffers = 0;
349     uint32_t mMaxV4L2BufferSize = 0;
350 
351     // Not protected by mLock (but might be used when mLock is locked)
352     sp<OutputThread> mOutputThread;
353 
354     // Stream ID -> Camera3Stream cache
355     std::unordered_map<int, Stream> mStreamMap;
356 
357     std::mutex mInflightFramesLock; // protect mInflightFrames
358     std::unordered_set<uint32_t>  mInflightFrames;
359 
360     // Stream ID -> circulating buffers map
361     std::map<int, CirculatingBuffers> mCirculatingBuffers;
362     // Protect mCirculatingBuffers, must not lock mLock after acquiring this lock
363     mutable Mutex mCbsLock;
364 
365     std::mutex mAfTriggerLock; // protect mAfTrigger
366     bool mAfTrigger = false;
367 
368     uint32_t mBlobBufferSize = 0;
369 
370     static HandleImporter sHandleImporter;
371 
372     /* Beginning of members not changed after initialize() */
373     using RequestMetadataQueue = MessageQueue<uint8_t, kSynchronizedReadWrite>;
374     std::unique_ptr<RequestMetadataQueue> mRequestMetadataQueue;
375     using ResultMetadataQueue = MessageQueue<uint8_t, kSynchronizedReadWrite>;
376     std::shared_ptr<ResultMetadataQueue> mResultMetadataQueue;
377 
378     // Protect against invokeProcessCaptureResultCallback()
379     Mutex mProcessCaptureResultLock;
380 
381     std::unordered_map<RequestTemplate, CameraMetadata> mDefaultRequests;
382 
383     const Size mMaxThumbResolution;
384     const Size mMaxJpegResolution;
385 
386     std::string mExifMake;
387     std::string mExifModel;
388     /* End of members not changed after initialize() */
389 
390 private:
391 
392     struct TrampolineSessionInterface_3_4 : public ICameraDeviceSession {
TrampolineSessionInterface_3_4ExternalCameraDeviceSession::TrampolineSessionInterface_3_4393         TrampolineSessionInterface_3_4(sp<ExternalCameraDeviceSession> parent) :
394                 mParent(parent) {}
395 
constructDefaultRequestSettingsExternalCameraDeviceSession::TrampolineSessionInterface_3_4396         virtual Return<void> constructDefaultRequestSettings(
397                 RequestTemplate type,
398                 V3_3::ICameraDeviceSession::constructDefaultRequestSettings_cb _hidl_cb) override {
399             return mParent->constructDefaultRequestSettings(type, _hidl_cb);
400         }
401 
configureStreamsExternalCameraDeviceSession::TrampolineSessionInterface_3_4402         virtual Return<void> configureStreams(
403                 const V3_2::StreamConfiguration& requestedConfiguration,
404                 V3_3::ICameraDeviceSession::configureStreams_cb _hidl_cb) override {
405             return mParent->configureStreams(requestedConfiguration, _hidl_cb);
406         }
407 
processCaptureRequestExternalCameraDeviceSession::TrampolineSessionInterface_3_4408         virtual Return<void> processCaptureRequest(const hidl_vec<V3_2::CaptureRequest>& requests,
409                 const hidl_vec<V3_2::BufferCache>& cachesToRemove,
410                 V3_3::ICameraDeviceSession::processCaptureRequest_cb _hidl_cb) override {
411             return mParent->processCaptureRequest(requests, cachesToRemove, _hidl_cb);
412         }
413 
getCaptureRequestMetadataQueueExternalCameraDeviceSession::TrampolineSessionInterface_3_4414         virtual Return<void> getCaptureRequestMetadataQueue(
415                 V3_3::ICameraDeviceSession::getCaptureRequestMetadataQueue_cb _hidl_cb) override  {
416             return mParent->getCaptureRequestMetadataQueue(_hidl_cb);
417         }
418 
getCaptureResultMetadataQueueExternalCameraDeviceSession::TrampolineSessionInterface_3_4419         virtual Return<void> getCaptureResultMetadataQueue(
420                 V3_3::ICameraDeviceSession::getCaptureResultMetadataQueue_cb _hidl_cb) override  {
421             return mParent->getCaptureResultMetadataQueue(_hidl_cb);
422         }
423 
flushExternalCameraDeviceSession::TrampolineSessionInterface_3_4424         virtual Return<Status> flush() override {
425             return mParent->flush();
426         }
427 
closeExternalCameraDeviceSession::TrampolineSessionInterface_3_4428         virtual Return<void> close() override {
429             return mParent->close();
430         }
431 
configureStreams_3_3ExternalCameraDeviceSession::TrampolineSessionInterface_3_4432         virtual Return<void> configureStreams_3_3(
433                 const V3_2::StreamConfiguration& requestedConfiguration,
434                 configureStreams_3_3_cb _hidl_cb) override {
435             return mParent->configureStreams_3_3(requestedConfiguration, _hidl_cb);
436         }
437 
configureStreams_3_4ExternalCameraDeviceSession::TrampolineSessionInterface_3_4438         virtual Return<void> configureStreams_3_4(
439                 const V3_4::StreamConfiguration& requestedConfiguration,
440                 configureStreams_3_4_cb _hidl_cb) override {
441             return mParent->configureStreams_3_4(requestedConfiguration, _hidl_cb);
442         }
443 
processCaptureRequest_3_4ExternalCameraDeviceSession::TrampolineSessionInterface_3_4444         virtual Return<void> processCaptureRequest_3_4(const hidl_vec<V3_4::CaptureRequest>& requests,
445                 const hidl_vec<V3_2::BufferCache>& cachesToRemove,
446                 ICameraDeviceSession::processCaptureRequest_3_4_cb _hidl_cb) override {
447             return mParent->processCaptureRequest_3_4(requests, cachesToRemove, _hidl_cb);
448         }
449 
450     private:
451         sp<ExternalCameraDeviceSession> mParent;
452     };
453 };
454 
455 }  // namespace implementation
456 }  // namespace V3_4
457 }  // namespace device
458 }  // namespace camera
459 }  // namespace hardware
460 }  // namespace android
461 
462 #endif  // ANDROID_HARDWARE_CAMERA_DEVICE_V3_4_EXTCAMERADEVICESESSION_H
463