Camera3Device.h revision c00a25ccce0734bf5627cf02d0c4fb3cf051ce15
1/*
2 * Copyright (C) 2013 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_SERVERS_CAMERA3DEVICE_H
18#define ANDROID_SERVERS_CAMERA3DEVICE_H
19
20#include <utils/Condition.h>
21#include <utils/Errors.h>
22#include <utils/List.h>
23#include <utils/Mutex.h>
24#include <utils/Thread.h>
25#include <utils/KeyedVector.h>
26#include <hardware/camera3.h>
27#include <camera/CaptureResult.h>
28#include <camera/camera2/ICameraDeviceUser.h>
29
30#include "common/CameraDeviceBase.h"
31#include "device3/StatusTracker.h"
32
33/**
34 * Function pointer types with C calling convention to
35 * use for HAL callback functions.
36 */
37extern "C" {
38    typedef void (callbacks_process_capture_result_t)(
39        const struct camera3_callback_ops *,
40        const camera3_capture_result_t *);
41
42    typedef void (callbacks_notify_t)(
43        const struct camera3_callback_ops *,
44        const camera3_notify_msg_t *);
45}
46
47namespace android {
48
49namespace camera3 {
50
51class Camera3Stream;
52class Camera3ZslStream;
53class Camera3OutputStreamInterface;
54class Camera3StreamInterface;
55
56}
57
58/**
59 * CameraDevice for HAL devices with version CAMERA_DEVICE_API_VERSION_3_0 or higher.
60 */
61class Camera3Device :
62            public CameraDeviceBase,
63            private camera3_callback_ops {
64  public:
65    Camera3Device(int id);
66
67    virtual ~Camera3Device();
68
69    /**
70     * CameraDeviceBase interface
71     */
72
73    virtual int      getId() const;
74
75    // Transitions to idle state on success.
76    virtual status_t initialize(camera_module_t *module);
77    virtual status_t disconnect();
78    virtual status_t dump(int fd, const Vector<String16> &args);
79    virtual const CameraMetadata& info() const;
80
81    // Capture and setStreamingRequest will configure streams if currently in
82    // idle state
83    virtual status_t capture(CameraMetadata &request, int64_t *lastFrameNumber = NULL);
84    virtual status_t captureList(const List<const CameraMetadata> &requests,
85                                 int64_t *lastFrameNumber = NULL);
86    virtual status_t setStreamingRequest(const CameraMetadata &request,
87                                         int64_t *lastFrameNumber = NULL);
88    virtual status_t setStreamingRequestList(const List<const CameraMetadata> &requests,
89                                             int64_t *lastFrameNumber = NULL);
90    virtual status_t clearStreamingRequest(int64_t *lastFrameNumber = NULL);
91
92    virtual status_t waitUntilRequestReceived(int32_t requestId, nsecs_t timeout);
93
94    // Actual stream creation/deletion is delayed until first request is submitted
95    // If adding streams while actively capturing, will pause device before adding
96    // stream, reconfiguring device, and unpausing.
97    virtual status_t createStream(sp<ANativeWindow> consumer,
98            uint32_t width, uint32_t height, int format, int *id);
99    virtual status_t createInputStream(
100            uint32_t width, uint32_t height, int format,
101            int *id);
102    virtual status_t createZslStream(
103            uint32_t width, uint32_t height,
104            int depth,
105            /*out*/
106            int *id,
107            sp<camera3::Camera3ZslStream>* zslStream);
108    virtual status_t createReprocessStreamFromStream(int outputId, int *id);
109
110    virtual status_t getStreamInfo(int id,
111            uint32_t *width, uint32_t *height, uint32_t *format);
112    virtual status_t setStreamTransform(int id, int transform);
113
114    virtual status_t deleteStream(int id);
115    virtual status_t deleteReprocessStream(int id);
116
117    virtual status_t createDefaultRequest(int templateId, CameraMetadata *request);
118
119    // Transitions to the idle state on success
120    virtual status_t waitUntilDrained();
121
122    virtual status_t setNotifyCallback(NotificationListener *listener);
123    virtual bool     willNotify3A();
124    virtual status_t waitForNextFrame(nsecs_t timeout);
125    virtual status_t getNextResult(CaptureResult *frame);
126
127    virtual status_t triggerAutofocus(uint32_t id);
128    virtual status_t triggerCancelAutofocus(uint32_t id);
129    virtual status_t triggerPrecaptureMetering(uint32_t id);
130
131    virtual status_t pushReprocessBuffer(int reprocessStreamId,
132            buffer_handle_t *buffer, wp<BufferReleasedListener> listener);
133
134    virtual status_t flush(int64_t *lastFrameNumber = NULL);
135
136    virtual uint32_t getDeviceVersion();
137
138    virtual ssize_t getJpegBufferSize(uint32_t width, uint32_t height) const;
139
140    // Methods called by subclasses
141    void             notifyStatus(bool idle); // updates from StatusTracker
142
143  private:
144    static const size_t        kDumpLockAttempts  = 10;
145    static const size_t        kDumpSleepDuration = 100000; // 0.10 sec
146    static const size_t        kInFlightWarnLimit = 20;
147    static const nsecs_t       kShutdownTimeout   = 5000000000; // 5 sec
148    static const nsecs_t       kActiveTimeout     = 500000000;  // 500 ms
149    struct                     RequestTrigger;
150    // minimal jpeg buffer size: 256KB + blob header
151    static const ssize_t       kMinJpegBufferSize = 256 * 1024 + sizeof(camera3_jpeg_blob);
152
153    // A lock to enforce serialization on the input/configure side
154    // of the public interface.
155    // Only locked by public methods inherited from CameraDeviceBase.
156    // Not locked by methods guarded by mOutputLock, since they may act
157    // concurrently to the input/configure side of the interface.
158    // Must be locked before mLock if both will be locked by a method
159    Mutex                      mInterfaceLock;
160
161    // The main lock on internal state
162    Mutex                      mLock;
163
164    // Camera device ID
165    const int                  mId;
166
167    /**** Scope for mLock ****/
168
169    camera3_device_t          *mHal3Device;
170
171    CameraMetadata             mDeviceInfo;
172
173    uint32_t                   mDeviceVersion;
174
175    enum Status {
176        STATUS_ERROR,
177        STATUS_UNINITIALIZED,
178        STATUS_UNCONFIGURED,
179        STATUS_CONFIGURED,
180        STATUS_ACTIVE
181    }                          mStatus;
182    Vector<Status>             mRecentStatusUpdates;
183    Condition                  mStatusChanged;
184
185    // Tracking cause of fatal errors when in STATUS_ERROR
186    String8                    mErrorCause;
187
188    // Mapping of stream IDs to stream instances
189    typedef KeyedVector<int, sp<camera3::Camera3OutputStreamInterface> >
190            StreamSet;
191
192    StreamSet                  mOutputStreams;
193    sp<camera3::Camera3Stream> mInputStream;
194    int                        mNextStreamId;
195    bool                       mNeedConfig;
196
197    // Whether to send state updates upstream
198    // Pause when doing transparent reconfiguration
199    bool                       mPauseStateNotify;
200
201    // Need to hold on to stream references until configure completes.
202    Vector<sp<camera3::Camera3StreamInterface> > mDeletedStreams;
203
204    // Whether the HAL will send partial result
205    bool                       mUsePartialResult;
206
207    // Number of partial results that will be delivered by the HAL.
208    uint32_t                   mNumPartialResults;
209
210    /**** End scope for mLock ****/
211
212    class CaptureRequest : public LightRefBase<CaptureRequest> {
213      public:
214        CameraMetadata                      mSettings;
215        sp<camera3::Camera3Stream>          mInputStream;
216        Vector<sp<camera3::Camera3OutputStreamInterface> >
217                                            mOutputStreams;
218        CaptureResultExtras                 mResultExtras;
219    };
220    typedef List<sp<CaptureRequest> > RequestList;
221
222    status_t checkStatusOkToCaptureLocked();
223
224    status_t convertMetadataListToRequestListLocked(
225            const List<const CameraMetadata> &metadataList,
226            /*out*/
227            RequestList *requestList);
228
229    status_t submitRequestsHelper(const List<const CameraMetadata> &requests, bool repeating,
230                                  int64_t *lastFrameNumber = NULL);
231
232    /**
233     * Get the last request submitted to the hal by the request thread.
234     *
235     * Takes mLock.
236     */
237    virtual CameraMetadata getLatestRequestLocked();
238
239    /**
240     * Pause processing and flush everything, but don't tell the clients.
241     * This is for reconfiguring outputs transparently when according to the
242     * CameraDeviceBase interface we shouldn't need to.
243     * Must be called with mLock and mInterfaceLock both held.
244     */
245    status_t internalPauseAndWaitLocked();
246
247    /**
248     * Resume work after internalPauseAndWaitLocked()
249     * Must be called with mLock and mInterfaceLock both held.
250     */
251    status_t internalResumeLocked();
252
253    /**
254     * Wait until status tracker tells us we've transitioned to the target state
255     * set, which is either ACTIVE when active==true or IDLE (which is any
256     * non-ACTIVE state) when active==false.
257     *
258     * Needs to be called with mLock and mInterfaceLock held.  This means there
259     * can ever only be one waiter at most.
260     *
261     * During the wait mLock is released.
262     *
263     */
264    status_t waitUntilStateThenRelock(bool active, nsecs_t timeout);
265
266    /**
267     * Implementation of waitUntilDrained. On success, will transition to IDLE state.
268     *
269     * Need to be called with mLock and mInterfaceLock held.
270     */
271    status_t waitUntilDrainedLocked();
272
273    /**
274     * Do common work for setting up a streaming or single capture request.
275     * On success, will transition to ACTIVE if in IDLE.
276     */
277    sp<CaptureRequest> setUpRequestLocked(const CameraMetadata &request);
278
279    /**
280     * Build a CaptureRequest request from the CameraDeviceBase request
281     * settings.
282     */
283    sp<CaptureRequest> createCaptureRequest(const CameraMetadata &request);
284
285    /**
286     * Take the currently-defined set of streams and configure the HAL to use
287     * them. This is a long-running operation (may be several hundered ms).
288     */
289    status_t           configureStreamsLocked();
290
291    /**
292     * Set device into an error state due to some fatal failure, and set an
293     * error message to indicate why. Only the first call's message will be
294     * used. The message is also sent to the log.
295     */
296    void               setErrorState(const char *fmt, ...);
297    void               setErrorStateV(const char *fmt, va_list args);
298    void               setErrorStateLocked(const char *fmt, ...);
299    void               setErrorStateLockedV(const char *fmt, va_list args);
300
301    /**
302     * Debugging trylock/spin method
303     * Try to acquire a lock a few times with sleeps between before giving up.
304     */
305    bool               tryLockSpinRightRound(Mutex& lock);
306
307    struct Size {
308        int width;
309        int height;
310        Size(int w, int h) : width(w), height(h){}
311    };
312
313    /**
314     * Helper function to get the largest Jpeg resolution (in area)
315     * Return Size(0, 0) if static metatdata is invalid
316     */
317    Size getMaxJpegResolution() const;
318
319    struct RequestTrigger {
320        // Metadata tag number, e.g. android.control.aePrecaptureTrigger
321        uint32_t metadataTag;
322        // Metadata value, e.g. 'START' or the trigger ID
323        int32_t entryValue;
324
325        // The last part of the fully qualified path, e.g. afTrigger
326        const char *getTagName() const {
327            return get_camera_metadata_tag_name(metadataTag) ?: "NULL";
328        }
329
330        // e.g. TYPE_BYTE, TYPE_INT32, etc.
331        int getTagType() const {
332            return get_camera_metadata_tag_type(metadataTag);
333        }
334    };
335
336    /**
337     * Thread for managing capture request submission to HAL device.
338     */
339    class RequestThread : public Thread {
340
341      public:
342
343        RequestThread(wp<Camera3Device> parent,
344                sp<camera3::StatusTracker> statusTracker,
345                camera3_device_t *hal3Device);
346
347        /**
348         * Call after stream (re)-configuration is completed.
349         */
350        void     configurationComplete();
351
352        /**
353         * Set or clear the list of repeating requests. Does not block
354         * on either. Use waitUntilPaused to wait until request queue
355         * has emptied out.
356         */
357        status_t setRepeatingRequests(const RequestList& requests,
358                                      /*out*/
359                                      int64_t *lastFrameNumber = NULL);
360        status_t clearRepeatingRequests(/*out*/
361                                        int64_t *lastFrameNumber = NULL);
362
363        status_t queueRequestList(List<sp<CaptureRequest> > &requests,
364                                  /*out*/
365                                  int64_t *lastFrameNumber = NULL);
366
367        /**
368         * Remove all queued and repeating requests, and pending triggers
369         */
370        status_t clear(/*out*/
371                       int64_t *lastFrameNumber = NULL);
372
373        /**
374         * Queue a trigger to be dispatched with the next outgoing
375         * process_capture_request. The settings for that request only
376         * will be temporarily rewritten to add the trigger tag/value.
377         * Subsequent requests will not be rewritten (for this tag).
378         */
379        status_t queueTrigger(RequestTrigger trigger[], size_t count);
380
381        /**
382         * Pause/unpause the capture thread. Doesn't block, so use
383         * waitUntilPaused to wait until the thread is paused.
384         */
385        void     setPaused(bool paused);
386
387        /**
388         * Wait until thread processes the capture request with settings'
389         * android.request.id == requestId.
390         *
391         * Returns TIMED_OUT in case the thread does not process the request
392         * within the timeout.
393         */
394        status_t waitUntilRequestProcessed(int32_t requestId, nsecs_t timeout);
395
396        /**
397         * Shut down the thread. Shutdown is asynchronous, so thread may
398         * still be running once this method returns.
399         */
400        virtual void requestExit();
401
402        /**
403         * Get the latest request that was sent to the HAL
404         * with process_capture_request.
405         */
406        CameraMetadata getLatestRequest() const;
407
408      protected:
409
410        virtual bool threadLoop();
411
412      private:
413        static int         getId(const wp<Camera3Device> &device);
414
415        status_t           queueTriggerLocked(RequestTrigger trigger);
416        // Mix-in queued triggers into this request
417        int32_t            insertTriggers(const sp<CaptureRequest> &request);
418        // Purge the queued triggers from this request,
419        //  restoring the old field values for those tags.
420        status_t           removeTriggers(const sp<CaptureRequest> &request);
421
422        // HAL workaround: Make sure a trigger ID always exists if
423        // a trigger does
424        status_t          addDummyTriggerIds(const sp<CaptureRequest> &request);
425
426        static const nsecs_t kRequestTimeout = 50e6; // 50 ms
427
428        // Waits for a request, or returns NULL if times out.
429        sp<CaptureRequest> waitForNextRequest();
430
431        // Return buffers, etc, for a request that couldn't be fully
432        // constructed. The buffers will be returned in the ERROR state
433        // to mark them as not having valid data.
434        // All arguments will be modified.
435        void cleanUpFailedRequest(camera3_capture_request_t &request,
436                sp<CaptureRequest> &nextRequest,
437                Vector<camera3_stream_buffer_t> &outputBuffers);
438
439        // Pause handling
440        bool               waitIfPaused();
441        void               unpauseForNewRequests();
442
443        // Relay error to parent device object setErrorState
444        void               setErrorState(const char *fmt, ...);
445
446        // If the input request is in mRepeatingRequests. Must be called with mRequestLock hold
447        bool isRepeatingRequestLocked(const sp<CaptureRequest>);
448
449        wp<Camera3Device>  mParent;
450        wp<camera3::StatusTracker>  mStatusTracker;
451        camera3_device_t  *mHal3Device;
452
453        const int          mId;       // The camera ID
454        int                mStatusId; // The RequestThread's component ID for
455                                      // status tracking
456
457        Mutex              mRequestLock;
458        Condition          mRequestSignal;
459        RequestList        mRequestQueue;
460        RequestList        mRepeatingRequests;
461
462        bool               mReconfigured;
463
464        // Used by waitIfPaused, waitForNextRequest, and waitUntilPaused
465        Mutex              mPauseLock;
466        bool               mDoPause;
467        Condition          mDoPauseSignal;
468        bool               mPaused;
469        Condition          mPausedSignal;
470
471        sp<CaptureRequest> mPrevRequest;
472        int32_t            mPrevTriggers;
473
474        uint32_t           mFrameNumber;
475
476        mutable Mutex      mLatestRequestMutex;
477        Condition          mLatestRequestSignal;
478        // android.request.id for latest process_capture_request
479        int32_t            mLatestRequestId;
480        CameraMetadata     mLatestRequest;
481
482        typedef KeyedVector<uint32_t/*tag*/, RequestTrigger> TriggerMap;
483        Mutex              mTriggerMutex;
484        TriggerMap         mTriggerMap;
485        TriggerMap         mTriggerRemovedMap;
486        TriggerMap         mTriggerReplacedMap;
487        uint32_t           mCurrentAfTriggerId;
488        uint32_t           mCurrentPreCaptureTriggerId;
489
490        int64_t            mRepeatingLastFrameNumber;
491    };
492    sp<RequestThread> mRequestThread;
493
494    /**
495     * In-flight queue for tracking completion of capture requests.
496     */
497
498    struct InFlightRequest {
499        // Set by notify() SHUTTER call.
500        nsecs_t captureTimestamp;
501        int     requestStatus;
502        // Set by process_capture_result call with valid metadata
503        bool    haveResultMetadata;
504        // Decremented by calls to process_capture_result with valid output
505        // and input buffers
506        int     numBuffersLeft;
507        CaptureResultExtras resultExtras;
508        // If this request has any input buffer
509        bool hasInputBuffer;
510
511        // Fields used by the partial result only
512        struct PartialResultInFlight {
513            // Set by process_capture_result once 3A has been sent to clients
514            bool    haveSent3A;
515            // Result metadata collected so far, when partial results are in use
516            CameraMetadata collectedResult;
517
518            PartialResultInFlight():
519                    haveSent3A(false) {
520            }
521        } partialResult;
522
523        // Default constructor needed by KeyedVector
524        InFlightRequest() :
525                captureTimestamp(0),
526                requestStatus(OK),
527                haveResultMetadata(false),
528                numBuffersLeft(0),
529                hasInputBuffer(false){
530        }
531
532        InFlightRequest(int numBuffers) :
533                captureTimestamp(0),
534                requestStatus(OK),
535                haveResultMetadata(false),
536                numBuffersLeft(numBuffers),
537                hasInputBuffer(false){
538        }
539
540        InFlightRequest(int numBuffers, CaptureResultExtras extras) :
541                captureTimestamp(0),
542                requestStatus(OK),
543                haveResultMetadata(false),
544                numBuffersLeft(numBuffers),
545                resultExtras(extras),
546                hasInputBuffer(false){
547        }
548
549        InFlightRequest(int numBuffers, CaptureResultExtras extras, bool hasInput) :
550                captureTimestamp(0),
551                requestStatus(OK),
552                haveResultMetadata(false),
553                numBuffersLeft(numBuffers),
554                resultExtras(extras),
555                hasInputBuffer(hasInput){
556        }
557};
558    // Map from frame number to the in-flight request state
559    typedef KeyedVector<uint32_t, InFlightRequest> InFlightMap;
560
561    Mutex                  mInFlightLock; // Protects mInFlightMap
562    InFlightMap            mInFlightMap;
563
564    status_t registerInFlight(uint32_t frameNumber,
565            int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput);
566
567    /**
568     * For the partial result, check if all 3A state fields are available
569     * and if so, queue up 3A-only result to the client. Returns true if 3A
570     * is sent.
571     */
572    bool processPartial3AResult(uint32_t frameNumber,
573            const CameraMetadata& partial, const CaptureResultExtras& resultExtras);
574
575    // Helpers for reading and writing 3A metadata into to/from partial results
576    template<typename T>
577    bool get3AResult(const CameraMetadata& result, int32_t tag,
578            T* value, uint32_t frameNumber);
579
580    template<typename T>
581    bool insert3AResult(CameraMetadata &result, int32_t tag, const T* value,
582            uint32_t frameNumber);
583    /**
584     * Tracking for idle detection
585     */
586    sp<camera3::StatusTracker> mStatusTracker;
587
588    /**
589     * Output result queue and current HAL device 3A state
590     */
591
592    // Lock for output side of device
593    Mutex                  mOutputLock;
594
595    /**** Scope for mOutputLock ****/
596
597    uint32_t               mNextResultFrameNumber;
598    uint32_t               mNextShutterFrameNumber;
599    List<CaptureResult>   mResultQueue;
600    Condition              mResultSignal;
601    NotificationListener  *mListener;
602
603    /**** End scope for mOutputLock ****/
604
605    /**
606     * Callback functions from HAL device
607     */
608    void processCaptureResult(const camera3_capture_result *result);
609
610    void notify(const camera3_notify_msg *msg);
611
612    /**
613     * Static callback forwarding methods from HAL to instance
614     */
615    static callbacks_process_capture_result_t sProcessCaptureResult;
616
617    static callbacks_notify_t sNotify;
618
619}; // class Camera3Device
620
621}; // namespace android
622
623#endif
624