• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #ifndef _ACAMERA_DEVICE_H
17 #define _ACAMERA_DEVICE_H
18 
19 #include "ACameraMetadata.h"
20 #include "utils.h"
21 
22 #include <aidl/android/frameworks/cameraservice/common/Status.h>
23 #include <aidl/android/frameworks/cameraservice/device/BnCameraDeviceCallback.h>
24 #include <aidl/android/frameworks/cameraservice/device/CaptureResultExtras.h>
25 #include <aidl/android/frameworks/cameraservice/device/ErrorCode.h>
26 #include <aidl/android/frameworks/cameraservice/device/CaptureMetadataInfo.h>
27 #include <aidl/android/frameworks/cameraservice/device/ICameraDeviceUser.h>
28 #include <aidl/android/frameworks/cameraservice/device/PhysicalCameraSettings.h>
29 #include <aidl/android/frameworks/cameraservice/device/PhysicalCaptureResultInfo.h>
30 #include <aidl/android/frameworks/cameraservice/device/StreamConfigurationMode.h>
31 #include <aidl/android/frameworks/cameraservice/device/SubmitInfo.h>
32 #include <aidl/android/frameworks/cameraservice/service/CameraStatusAndId.h>
33 #include <atomic>
34 #include <camera/NdkCameraCaptureSession.h>
35 #include <camera/NdkCameraManager.h>
36 #include <fmq/AidlMessageQueue.h>
37 #include <fmq/MessageQueue.h>
38 #include <map>
39 #include <media/stagefright/foundation/AHandler.h>
40 #include <media/stagefright/foundation/ALooper.h>
41 #include <media/stagefright/foundation/AMessage.h>
42 #include <memory>
43 #include <set>
44 #include <utility>
45 #include <utils/List.h>
46 #include <utils/Mutex.h>
47 #include <utils/StrongPointer.h>
48 #include <utils/Vector.h>
49 #include <vector>
50 
51 namespace android {
52 namespace acam {
53 
54 using ::aidl::android::frameworks::cameraservice::common::Status;
55 using ::aidl::android::frameworks::cameraservice::device::BnCameraDeviceCallback;
56 using ::aidl::android::frameworks::cameraservice::device::CaptureResultExtras;
57 using ::aidl::android::frameworks::cameraservice::device::ErrorCode;
58 using ::aidl::android::frameworks::cameraservice::device::CaptureMetadataInfo;
59 using ::aidl::android::frameworks::cameraservice::device::ICameraDeviceCallback;
60 using ::aidl::android::frameworks::cameraservice::device::ICameraDeviceUser;
61 using ::aidl::android::frameworks::cameraservice::device::OutputConfiguration;
62 using ::aidl::android::frameworks::cameraservice::device::PhysicalCameraSettings;
63 using ::aidl::android::frameworks::cameraservice::device::PhysicalCaptureResultInfo;
64 using ::aidl::android::frameworks::cameraservice::device::StreamConfigurationMode;
65 using ::aidl::android::frameworks::cameraservice::device::SubmitInfo;
66 using ::aidl::android::frameworks::cameraservice::service::CameraStatusAndId;
67 using ::aidl::android::hardware::common::fmq::SynchronizedReadWrite;
68 using ::android::AidlMessageQueue;
69 
70 
71 using ResultMetadataQueue = AidlMessageQueue<int8_t, SynchronizedReadWrite>;
72 using RequestMetadataQueue = AidlMessageQueue<int8_t, SynchronizedReadWrite>;
73 
74 using utils::CaptureRequest;
75 
76 // Wrap ACameraCaptureFailure so it can be ref-counted
77 struct CameraCaptureFailure : public RefBase, public ACameraCaptureFailure { };
78 
79 // Wrap PhysicalCaptureResultInfo so that it can be ref-counted
80 struct PhysicalCaptureResultInfoLocal {
81     std::string physicalCameraId;
82     CameraMetadata physicalMetadata;
83 };
84 
85 struct ACameraPhysicalCaptureResultInfo: public RefBase {
ACameraPhysicalCaptureResultInfoACameraPhysicalCaptureResultInfo86     ACameraPhysicalCaptureResultInfo(const std::vector<PhysicalCaptureResultInfoLocal>& info,
87             int64_t frameNumber) :
88         mPhysicalResultInfo(info), mFrameNumber(frameNumber) {}
89 
90     std::vector<PhysicalCaptureResultInfoLocal> mPhysicalResultInfo;
91     int64_t mFrameNumber;
92 };
93 
94 class CameraDevice final : public std::enable_shared_from_this<CameraDevice> {
95   public:
96     CameraDevice(const char* id, ACameraDevice_StateCallbacks* cb,
97                   sp<ACameraMetadata> chars,
98                   ACameraDevice* wrapper);
99     ~CameraDevice();
100 
101     // Called to initialize fields that require shared_ptr to `this`
102     void init();
103 
getId()104     inline const char* getId() const { return mCameraId.c_str(); }
105 
106     camera_status_t createCaptureRequest(
107             ACameraDevice_request_template templateId,
108             const ACameraIdList* physicalCameraIdList,
109             ACaptureRequest** request) const;
110 
111     camera_status_t createCaptureSession(
112             const ACaptureSessionOutputContainer*       outputs,
113             const ACaptureRequest* sessionParameters,
114             const ACameraCaptureSession_stateCallbacks* callbacks,
115             /*out*/ACameraCaptureSession** session);
116 
117     camera_status_t isSessionConfigurationSupported(
118             const ACaptureSessionOutputContainer* sessionOutputContainer) const;
119 
120     // Callbacks from camera service
121     class ServiceCallback : public BnCameraDeviceCallback {
122       public:
ServiceCallback(std::weak_ptr<CameraDevice> device)123         explicit ServiceCallback(std::weak_ptr<CameraDevice> device) :
124               mDevice(std::move(device)) {}
125 
126         ndk::ScopedAStatus onDeviceError(ErrorCode in_errorCode,
127                                          const CaptureResultExtras& in_resultExtras) override;
128         ndk::ScopedAStatus onDeviceIdle() override;
129 
130         ndk::ScopedAStatus onCaptureStarted(const CaptureResultExtras& in_resultExtras,
131                                             int64_t in_timestamp) override;
132         ndk::ScopedAStatus onPrepared(int32_t in_streamId) override;
133         ndk::ScopedAStatus onRepeatingRequestError(int64_t in_lastFrameNumber,
134                                                    int32_t in_repeatingRequestId) override;
135         ndk::ScopedAStatus onResultReceived(const CaptureMetadataInfo& in_result,
136                                             const CaptureResultExtras& in_resultExtras,
137                                             const std::vector<PhysicalCaptureResultInfo>&
138                                                     in_physicalCaptureResultInfos) override;
139 
140       private:
141         camera_status_t readOneResultMetadata(const CaptureMetadataInfo& captureMetadataInfo,
142                 ResultMetadataQueue* metadataQueue, CameraMetadata* metadata);
143         const std::weak_ptr<CameraDevice> mDevice;
144     };
getServiceCallback()145     inline std::shared_ptr<BnCameraDeviceCallback> getServiceCallback() {
146         return mServiceCallback;
147     };
148 
149     // Camera device is only functional after remote being set
150     void setRemoteDevice(std::shared_ptr<ICameraDeviceUser> remote);
151 
152     bool setDeviceMetadataQueues();
getWrapper()153     inline ACameraDevice* getWrapper() const { return mWrapper; };
154 
155     // Stop the looper thread and unregister the handler
156     void stopLooperAndDisconnect();
157 
158   private:
159     friend ACameraCaptureSession;
160     friend ACameraDevice;
161 
162     camera_status_t checkCameraClosedOrErrorLocked() const;
163 
164     // device goes into fatal error state after this
165     void setCameraDeviceErrorLocked(camera_status_t error);
166 
167     void disconnectLocked(sp<ACameraCaptureSession>& session); // disconnect from camera service
168 
169     camera_status_t stopRepeatingLocked();
170 
171     camera_status_t flushLocked(ACameraCaptureSession*);
172 
173     camera_status_t waitUntilIdleLocked();
174 
175     template<class T>
176     camera_status_t captureLocked(sp<ACameraCaptureSession> session,
177             /*optional*/T* cbs,
178             int numRequests, ACaptureRequest** requests,
179             /*optional*/int* captureSequenceId);
180 
181     template<class T>
182     camera_status_t setRepeatingRequestsLocked(sp<ACameraCaptureSession> session,
183             /*optional*/T* cbs,
184             int numRequests, ACaptureRequest** requests,
185             /*optional*/int* captureSequenceId);
186 
187     template<class T>
188     camera_status_t submitRequestsLocked(
189             sp<ACameraCaptureSession> session,
190             /*optional*/T* cbs,
191             int numRequests, ACaptureRequest** requests,
192             /*out*/int* captureSequenceId,
193             bool isRepeating);
194 
195     void addRequestSettingsMetadata(ACaptureRequest *aCaptureRequest, sp<CaptureRequest> &req);
196 
197     camera_status_t updateOutputConfigurationLocked(ACaptureSessionOutput *output);
198 
199     camera_status_t prepareLocked(ANativeWindow *window);
200 
201     // Since this writes to ICameraDeviceUser's fmq, clients must take care that:
202     //   a) This function is called serially.
203     //   b) This function is called in accordance with ICameraDeviceUser.submitRequestList,
204     //      otherwise, the wrong capture request might have the wrong settings
205     //      metadata associated with it.
206     camera_status_t allocateCaptureRequestLocked(
207             const ACaptureRequest* request, sp<CaptureRequest>& outReq);
208     void allocateOneCaptureRequestMetadata(
209             PhysicalCameraSettings& cameraSettings,
210             const std::string& id, const sp<ACameraMetadata>& metadata);
211 
212     static ACaptureRequest* allocateACaptureRequest(sp<CaptureRequest>& req, const char* deviceId);
213     static void freeACaptureRequest(ACaptureRequest*);
214 
215     // only For session to hold device lock
216     // Always grab device lock before grabbing session lock
lockDeviceForSessionOps()217     void lockDeviceForSessionOps() const { mDeviceLock.lock(); };
unlockDevice()218     void unlockDevice() const { mDeviceLock.unlock(); };
219 
220     // For capture session to notify its end of life
221     void notifySessionEndOfLifeLocked(ACameraCaptureSession* session);
222 
223     camera_status_t configureStreamsLocked(const ACaptureSessionOutputContainer* outputs,
224            const ACaptureRequest* sessionParameters, nsecs_t startTimeNs);
225 
226     // Input message will be posted and cleared after this returns
227     void postSessionMsgAndCleanup(sp<AMessage>& msg);
228 
229     mutable Mutex mDeviceLock;
230     const std::string mCameraId;                          // Camera ID
231     const ACameraDevice_StateCallbacks mAppCallbacks; // Callback to app
232     const sp<ACameraMetadata> mChars;    // Camera characteristics
233     std::shared_ptr<ServiceCallback> mServiceCallback;
234     ACameraDevice* mWrapper;
235 
236     // stream id -> pair of (ACameraWindowType* from application, OutputConfiguration used for
237     // camera service)
238     std::map<int, std::pair<ANativeWindow *, OutputConfiguration>> mConfiguredOutputs;
239 
240     // TODO: maybe a bool will suffice for synchronous implementation?
241     std::atomic_bool mClosing;
isClosed()242     inline bool isClosed() { return mClosing; }
243 
244     bool mInError = false;
245     camera_status_t mError = ACAMERA_OK;
246     void onCaptureErrorLocked(
247             ErrorCode errorCode,
248             const CaptureResultExtras& resultExtras);
249 
250     bool mIdle = true;
251     // This will avoid a busy session being deleted before it's back to idle state
252     sp<ACameraCaptureSession> mBusySession;
253 
254     std::shared_ptr<ICameraDeviceUser> mRemote;
255 
256     // Looper thread to handle callback to app
257     sp<ALooper> mCbLooper;
258     // definition of handler and message
259     enum {
260         // Device state callbacks
261         kWhatOnDisconnected,   // onDisconnected
262         kWhatOnError,          // onError
263         // Session state callbacks
264         kWhatSessionStateCb,   // onReady, onActive
265         // Capture callbacks
266         kWhatCaptureStart,     // onCaptureStarted
267         kWhatCaptureStart2,     // onCaptureStarted2
268         kWhatCaptureResult,    // onCaptureProgressed, onCaptureCompleted
269         kWhatLogicalCaptureResult, // onLogicalCameraCaptureCompleted
270         kWhatCaptureFail,      // onCaptureFailed
271         kWhatLogicalCaptureFail, // onLogicalCameraCaptureFailed
272         kWhatCaptureSeqEnd,    // onCaptureSequenceCompleted
273         kWhatCaptureSeqAbort,  // onCaptureSequenceAborted
274         kWhatCaptureBufferLost, // onCaptureBufferLost
275         kWhatPreparedCb, // onPrepared
276         // Internal cleanup
277         kWhatCleanUpSessions   // Cleanup cached sp<ACameraCaptureSession>
278     };
279     static const char* kContextKey;
280     static const char* kDeviceKey;
281     static const char* kErrorCodeKey;
282     static const char* kCallbackFpKey;
283     static const char* kSessionSpKey;
284     static const char* kCaptureRequestKey;
285     static const char* kTimeStampKey;
286     static const char* kCaptureResultKey;
287     static const char* kPhysicalCaptureResultKey;
288     static const char* kCaptureFailureKey;
289     static const char* kSequenceIdKey;
290     static const char* kFrameNumberKey;
291     static const char* kAnwKey;
292     static const char* kFailingPhysicalCameraId;
293 
294     class CallbackHandler : public AHandler {
295       public:
296         explicit CallbackHandler(const char *id);
297         void onMessageReceived(const sp<AMessage> &msg) override;
298 
299       private:
300         std::string mId;
301         // This handler will cache all capture session sp until kWhatCleanUpSessions
302         // is processed. This is used to guarantee the last session reference is always
303         // being removed in callback thread without holding camera device lock
304         std::vector<sp<ACameraCaptureSession>> mCachedSessions;
305     };
306     sp<CallbackHandler> mHandler;
307 
308     /***********************************
309      * Capture session related members *
310      ***********************************/
311     // The current active session
312     wp<ACameraCaptureSession> mCurrentSession;
313     bool mFlushing = false;
314 
315     int mNextSessionId = 0;
316     // TODO: might need another looper/handler to handle callbacks from service
317 
318     static const int REQUEST_ID_NONE = -1;
319     int mRepeatingSequenceId = REQUEST_ID_NONE;
320 
321     // sequence id -> last frame number map
322     std::map<int32_t, int64_t> mSequenceLastFrameNumberMap;
323 
324     struct CallbackHolder {
325         CallbackHolder(sp<ACameraCaptureSession>          session,
326                        std::vector<sp<CaptureRequest>>   requests,
327                        bool                               isRepeating,
328                        ACameraCaptureSession_captureCallbacks* cbs);
329         CallbackHolder(sp<ACameraCaptureSession>          session,
330                        std::vector<sp<CaptureRequest>>   requests,
331                        bool                               isRepeating,
332                        ACameraCaptureSession_logicalCamera_captureCallbacks* lcbs);
333         CallbackHolder(sp<ACameraCaptureSession>          session,
334                        std::vector<sp<CaptureRequest> >  requests,
335                        bool                               isRepeating,
336                        ACameraCaptureSession_captureCallbacksV2* cbs);
337         CallbackHolder(sp<ACameraCaptureSession>          session,
338                        std::vector<sp<CaptureRequest> >  requests,
339                        bool                               isRepeating,
340                        ACameraCaptureSession_logicalCamera_captureCallbacksV2* lcbs);
clearCallbacksCallbackHolder341         void clearCallbacks() {
342             mContext = nullptr;
343             mOnCaptureStarted = nullptr;
344             mOnCaptureStarted2 = nullptr;
345             mOnCaptureProgressed = nullptr;
346             mOnCaptureCompleted = nullptr;
347             mOnLogicalCameraCaptureCompleted = nullptr;
348             mOnLogicalCameraCaptureFailed = nullptr;
349             mOnCaptureFailed = nullptr;
350             mOnCaptureSequenceCompleted = nullptr;
351             mOnCaptureSequenceAborted = nullptr;
352             mOnCaptureBufferLost = nullptr;
353         }
354 
355         template <class T>
initCaptureCallbacksV2CallbackHolder356         void initCaptureCallbacksV2(T* cbs) {
357             clearCallbacks();
358             if (cbs != nullptr) {
359                 mContext = cbs->context;
360                 mOnCaptureStarted2 = cbs->onCaptureStarted;
361                 mOnCaptureProgressed = cbs->onCaptureProgressed;
362                 mOnCaptureSequenceCompleted = cbs->onCaptureSequenceCompleted;
363                 mOnCaptureSequenceAborted = cbs->onCaptureSequenceAborted;
364                 mOnCaptureBufferLost = cbs->onCaptureBufferLost;
365             }
366         }
367 
368         template <class T>
initCaptureCallbacksCallbackHolder369         void initCaptureCallbacks(T* cbs) {
370             clearCallbacks();
371             if (cbs != nullptr) {
372                 mContext = cbs->context;
373                 mOnCaptureStarted = cbs->onCaptureStarted;
374                 mOnCaptureProgressed = cbs->onCaptureProgressed;
375                 mOnCaptureSequenceCompleted = cbs->onCaptureSequenceCompleted;
376                 mOnCaptureSequenceAborted = cbs->onCaptureSequenceAborted;
377                 mOnCaptureBufferLost = cbs->onCaptureBufferLost;
378             }
379         }
380 
381         sp<ACameraCaptureSession>   mSession;
382         std::vector<sp<CaptureRequest>>  mRequests;
383         const bool                  mIsRepeating;
384         const bool                  mIs2Callback;
385         const bool                  mIsLogicalCameraCallback;
386 
387         void*                       mContext;
388         ACameraCaptureSession_captureCallback_start mOnCaptureStarted;
389         ACameraCaptureSession_captureCallback_startV2 mOnCaptureStarted2;
390         ACameraCaptureSession_captureCallback_result mOnCaptureProgressed;
391         ACameraCaptureSession_captureCallback_result mOnCaptureCompleted;
392         ACameraCaptureSession_logicalCamera_captureCallback_result mOnLogicalCameraCaptureCompleted;
393         ACameraCaptureSession_logicalCamera_captureCallback_failed mOnLogicalCameraCaptureFailed;
394         ACameraCaptureSession_captureCallback_failed mOnCaptureFailed;
395         ACameraCaptureSession_captureCallback_sequenceEnd mOnCaptureSequenceCompleted;
396         ACameraCaptureSession_captureCallback_sequenceAbort mOnCaptureSequenceAborted;
397         ACameraCaptureSession_captureCallback_bufferLost mOnCaptureBufferLost;
398     };
399     // sequence id -> callbacks map
400     std::map<int, CallbackHolder> mSequenceCallbackMap;
401 
402     static const int64_t NO_FRAMES_CAPTURED = -1;
403     class FrameNumberTracker {
404       public:
405         // TODO: Called in onResultReceived and onCaptureErrorLocked
406         void updateTracker(int64_t frameNumber, bool isError);
getCompletedFrameNumber()407         inline int64_t getCompletedFrameNumber() { return mCompletedFrameNumber; }
408       private:
409         void update();
410         void updateCompletedFrameNumber(int64_t frameNumber);
411 
412         int64_t mCompletedFrameNumber = NO_FRAMES_CAPTURED;
413         List<int64_t> mSkippedFrameNumbers;
414         std::set<int64_t> mFutureErrorSet;
415     };
416     FrameNumberTracker mFrameNumberTracker;
417 
418     void checkRepeatingSequenceCompleteLocked(const int sequenceId, const int64_t lastFrameNumber);
419     void checkAndFireSequenceCompleteLocked();
420 
421     // Misc variables
422     int32_t mShadingMapSize[2];   // const after constructor
423     int32_t mPartialResultCount;  // const after constructor
424     std::shared_ptr<RequestMetadataQueue> mCaptureRequestMetadataQueue = nullptr;
425     std::shared_ptr<ResultMetadataQueue> mCaptureResultMetadataQueue = nullptr;
426 };
427 
428 } // namespace acam;
429 } // namespace android;
430 
431 /**
432  * ACameraDevice opaque struct definition
433  * Leave outside of android namespace because it's NDK struct
434  */
435 struct ACameraDevice {
ACameraDeviceACameraDevice436     ACameraDevice(const char* id, ACameraDevice_StateCallbacks* cb,
437                   sp<ACameraMetadata> chars) :
438             mDevice(std::make_shared<android::acam::CameraDevice>(id, cb,
439                                                                 std::move(chars), this)) {
440         mDevice->init();
441     }
442 
443     ~ACameraDevice();
444     /*******************
445      * NDK public APIs *
446      *******************/
getIdACameraDevice447     inline const char* getId() const { return mDevice->getId(); }
448 
createCaptureRequestACameraDevice449     camera_status_t createCaptureRequest(
450             ACameraDevice_request_template templateId,
451             const ACameraIdList* physicalCameraIdList,
452             ACaptureRequest** request) const {
453         return mDevice->createCaptureRequest(templateId, physicalCameraIdList, request);
454     }
455 
createCaptureSessionACameraDevice456     camera_status_t createCaptureSession(
457             const ACaptureSessionOutputContainer*       outputs,
458             const ACaptureRequest* sessionParameters,
459             const ACameraCaptureSession_stateCallbacks* callbacks,
460             /*out*/ACameraCaptureSession** session) {
461         return mDevice->createCaptureSession(outputs, sessionParameters, callbacks, session);
462     }
463 
isSessionConfigurationSupportedACameraDevice464     camera_status_t isSessionConfigurationSupported(
465             const ACaptureSessionOutputContainer* sessionOutputContainer) const {
466         return mDevice->isSessionConfigurationSupported(sessionOutputContainer);
467     }
468 
469     /***********************
470      * Device interal APIs *
471      ***********************/
getServiceCallbackACameraDevice472     inline std::shared_ptr<android::acam::BnCameraDeviceCallback> getServiceCallback() {
473         return mDevice->getServiceCallback();
474     };
475 
476     // Camera device is only functional after remote being set
setRemoteDeviceACameraDevice477     inline void setRemoteDevice(std::shared_ptr<
478             ::aidl::android::frameworks::cameraservice::device::ICameraDeviceUser> remote) {
479         mDevice->setRemoteDevice(remote);
480     }
setDeviceMetadataQueuesACameraDevice481     inline bool setDeviceMetadataQueues() {
482         return mDevice->setDeviceMetadataQueues();
483     }
484   private:
485     std::shared_ptr<android::acam::CameraDevice> mDevice;
486 };
487 
488 #endif // _ACAMERA_DEVICE_H
489