[go: nahoru, domu]

Camera3Device.h revision 4c060997514cb37aec9a9a7cec02a3f257d3a74d
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 <utils/Timers.h>
27#include <hardware/camera3.h>
28#include <camera/CaptureResult.h>
29
30#include "common/CameraDeviceBase.h"
31#include "device3/StatusTracker.h"
32#include "device3/Camera3BufferManager.h"
33
34/**
35 * Function pointer types with C calling convention to
36 * use for HAL callback functions.
37 */
38extern "C" {
39    typedef void (callbacks_process_capture_result_t)(
40        const struct camera3_callback_ops *,
41        const camera3_capture_result_t *);
42
43    typedef void (callbacks_notify_t)(
44        const struct camera3_callback_ops *,
45        const camera3_notify_msg_t *);
46}
47
48namespace android {
49
50namespace camera3 {
51
52class Camera3Stream;
53class Camera3ZslStream;
54class Camera3OutputStreamInterface;
55class Camera3StreamInterface;
56
57}
58
59/**
60 * CameraDevice for HAL devices with version CAMERA_DEVICE_API_VERSION_3_0 or higher.
61 */
62class Camera3Device :
63            public CameraDeviceBase,
64            private camera3_callback_ops {
65  public:
66
67    Camera3Device(int id);
68
69    virtual ~Camera3Device();
70
71    /**
72     * CameraDeviceBase interface
73     */
74
75    virtual int      getId() const;
76
77    // Transitions to idle state on success.
78    virtual status_t initialize(CameraModule *module);
79    virtual status_t disconnect();
80    virtual status_t dump(int fd, const Vector<String16> &args);
81    virtual const CameraMetadata& info() const;
82
83    // Capture and setStreamingRequest will configure streams if currently in
84    // idle state
85    virtual status_t capture(CameraMetadata &request, int64_t *lastFrameNumber = NULL);
86    virtual status_t captureList(const List<const CameraMetadata> &requests,
87                                 int64_t *lastFrameNumber = NULL);
88    virtual status_t setStreamingRequest(const CameraMetadata &request,
89                                         int64_t *lastFrameNumber = NULL);
90    virtual status_t setStreamingRequestList(const List<const CameraMetadata> &requests,
91                                             int64_t *lastFrameNumber = NULL);
92    virtual status_t clearStreamingRequest(int64_t *lastFrameNumber = NULL);
93
94    virtual status_t waitUntilRequestReceived(int32_t requestId, nsecs_t timeout);
95
96    // Actual stream creation/deletion is delayed until first request is submitted
97    // If adding streams while actively capturing, will pause device before adding
98    // stream, reconfiguring device, and unpausing.
99    virtual status_t createStream(sp<Surface> consumer,
100            uint32_t width, uint32_t height, int format,
101            android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
102            int streamSetId = camera3::CAMERA3_STREAM_SET_ID_INVALID);
103    virtual status_t createInputStream(
104            uint32_t width, uint32_t height, int format,
105            int *id);
106    virtual status_t createZslStream(
107            uint32_t width, uint32_t height,
108            int depth,
109            /*out*/
110            int *id,
111            sp<camera3::Camera3ZslStream>* zslStream);
112    virtual status_t createReprocessStreamFromStream(int outputId, int *id);
113
114    virtual status_t getStreamInfo(int id,
115            uint32_t *width, uint32_t *height,
116            uint32_t *format, android_dataspace *dataSpace);
117    virtual status_t setStreamTransform(int id, int transform);
118
119    virtual status_t deleteStream(int id);
120    virtual status_t deleteReprocessStream(int id);
121
122    virtual status_t configureStreams(bool isConstraiedHighSpeed = false);
123    virtual status_t getInputBufferProducer(
124            sp<IGraphicBufferProducer> *producer);
125
126    virtual status_t createDefaultRequest(int templateId, CameraMetadata *request);
127
128    // Transitions to the idle state on success
129    virtual status_t waitUntilDrained();
130
131    virtual status_t setNotifyCallback(NotificationListener *listener);
132    virtual bool     willNotify3A();
133    virtual status_t waitForNextFrame(nsecs_t timeout);
134    virtual status_t getNextResult(CaptureResult *frame);
135
136    virtual status_t triggerAutofocus(uint32_t id);
137    virtual status_t triggerCancelAutofocus(uint32_t id);
138    virtual status_t triggerPrecaptureMetering(uint32_t id);
139
140    virtual status_t pushReprocessBuffer(int reprocessStreamId,
141            buffer_handle_t *buffer, wp<BufferReleasedListener> listener);
142
143    virtual status_t flush(int64_t *lastFrameNumber = NULL);
144
145    virtual status_t prepare(int streamId);
146
147    virtual status_t tearDown(int streamId);
148
149    virtual status_t addBufferListenerForStream(int streamId,
150            wp<camera3::Camera3StreamBufferListener> listener);
151
152    virtual status_t prepare(int maxCount, int streamId);
153
154    virtual uint32_t getDeviceVersion();
155
156    virtual ssize_t getJpegBufferSize(uint32_t width, uint32_t height) const;
157    ssize_t getPointCloudBufferSize() const;
158    ssize_t getRawOpaqueBufferSize(int32_t width, int32_t height) const;
159
160    // Methods called by subclasses
161    void             notifyStatus(bool idle); // updates from StatusTracker
162
163  private:
164    static const size_t        kDumpLockAttempts  = 10;
165    static const size_t        kDumpSleepDuration = 100000; // 0.10 sec
166    static const nsecs_t       kShutdownTimeout   = 5000000000; // 5 sec
167    static const nsecs_t       kActiveTimeout     = 500000000;  // 500 ms
168    static const size_t        kInFlightWarnLimit = 20;
169    static const size_t        kInFlightWarnLimitHighSpeed = 256; // batch size 32 * pipe depth 8
170    // SCHED_FIFO priority for request submission thread in HFR mode
171    static const int           kConstrainedHighSpeedThreadPriority = 1;
172
173    struct                     RequestTrigger;
174    // minimal jpeg buffer size: 256KB + blob header
175    static const ssize_t       kMinJpegBufferSize = 256 * 1024 + sizeof(camera3_jpeg_blob);
176    // Constant to use for stream ID when one doesn't exist
177    static const int           NO_STREAM = -1;
178
179    // A lock to enforce serialization on the input/configure side
180    // of the public interface.
181    // Only locked by public methods inherited from CameraDeviceBase.
182    // Not locked by methods guarded by mOutputLock, since they may act
183    // concurrently to the input/configure side of the interface.
184    // Must be locked before mLock if both will be locked by a method
185    Mutex                      mInterfaceLock;
186
187    // The main lock on internal state
188    Mutex                      mLock;
189
190    // Camera device ID
191    const int                  mId;
192
193    // Flag indicating is the current active stream configuration is constrained high speed.
194    bool                       mIsConstrainedHighSpeedConfiguration;
195
196    /**** Scope for mLock ****/
197
198    camera3_device_t          *mHal3Device;
199
200    CameraMetadata             mDeviceInfo;
201
202    CameraMetadata             mRequestTemplateCache[CAMERA3_TEMPLATE_COUNT];
203
204    uint32_t                   mDeviceVersion;
205
206    // whether Camera3Device should derive ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST for
207    // backward compatibility. Should not be changed after initialization.
208    bool                       mDerivePostRawSensKey = false;
209
210    struct Size {
211        uint32_t width;
212        uint32_t height;
213        Size(uint32_t w = 0, uint32_t h = 0) : width(w), height(h){}
214    };
215    // Map from format to size.
216    Vector<Size>               mSupportedOpaqueInputSizes;
217
218    enum Status {
219        STATUS_ERROR,
220        STATUS_UNINITIALIZED,
221        STATUS_UNCONFIGURED,
222        STATUS_CONFIGURED,
223        STATUS_ACTIVE
224    }                          mStatus;
225
226    // Only clear mRecentStatusUpdates, mStatusWaiters from waitUntilStateThenRelock
227    Vector<Status>             mRecentStatusUpdates;
228    int                        mStatusWaiters;
229
230    Condition                  mStatusChanged;
231
232    // Tracking cause of fatal errors when in STATUS_ERROR
233    String8                    mErrorCause;
234
235    // Mapping of stream IDs to stream instances
236    typedef KeyedVector<int, sp<camera3::Camera3OutputStreamInterface> >
237            StreamSet;
238
239    StreamSet                  mOutputStreams;
240    sp<camera3::Camera3Stream> mInputStream;
241    int                        mNextStreamId;
242    bool                       mNeedConfig;
243
244    int                        mDummyStreamId;
245
246    // Whether to send state updates upstream
247    // Pause when doing transparent reconfiguration
248    bool                       mPauseStateNotify;
249
250    // Need to hold on to stream references until configure completes.
251    Vector<sp<camera3::Camera3StreamInterface> > mDeletedStreams;
252
253    // Whether the HAL will send partial result
254    bool                       mUsePartialResult;
255
256    // Number of partial results that will be delivered by the HAL.
257    uint32_t                   mNumPartialResults;
258
259    /**** End scope for mLock ****/
260
261    // The offset converting from clock domain of other subsystem
262    // (video/hardware composer) to that of camera. Assumption is that this
263    // offset won't change during the life cycle of the camera device. In other
264    // words, camera device shouldn't be open during CPU suspend.
265    nsecs_t                    mTimestampOffset;
266
267    typedef struct AeTriggerCancelOverride {
268        bool applyAeLock;
269        uint8_t aeLock;
270        bool applyAePrecaptureTrigger;
271        uint8_t aePrecaptureTrigger;
272    } AeTriggerCancelOverride_t;
273
274    class CaptureRequest : public LightRefBase<CaptureRequest> {
275      public:
276        CameraMetadata                      mSettings;
277        sp<camera3::Camera3Stream>          mInputStream;
278        camera3_stream_buffer_t             mInputBuffer;
279        Vector<sp<camera3::Camera3OutputStreamInterface> >
280                                            mOutputStreams;
281        CaptureResultExtras                 mResultExtras;
282        // Used to cancel AE precapture trigger for devices doesn't support
283        // CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL
284        AeTriggerCancelOverride_t           mAeTriggerCancelOverride;
285        // The number of requests that should be submitted to HAL at a time.
286        // For example, if batch size is 8, this request and the following 7
287        // requests will be submitted to HAL at a time. The batch size for
288        // the following 7 requests will be ignored by the request thread.
289        int                                 mBatchSize;
290    };
291    typedef List<sp<CaptureRequest> > RequestList;
292
293    status_t checkStatusOkToCaptureLocked();
294
295    status_t convertMetadataListToRequestListLocked(
296            const List<const CameraMetadata> &metadataList,
297            /*out*/
298            RequestList *requestList);
299
300    status_t submitRequestsHelper(const List<const CameraMetadata> &requests, bool repeating,
301                                  int64_t *lastFrameNumber = NULL);
302
303    /**
304     * Get the last request submitted to the hal by the request thread.
305     *
306     * Takes mLock.
307     */
308    virtual CameraMetadata getLatestRequestLocked();
309
310    /**
311     * Update the current device status and wake all waiting threads.
312     *
313     * Must be called with mLock held.
314     */
315    void internalUpdateStatusLocked(Status status);
316
317    /**
318     * Pause processing and flush everything, but don't tell the clients.
319     * This is for reconfiguring outputs transparently when according to the
320     * CameraDeviceBase interface we shouldn't need to.
321     * Must be called with mLock and mInterfaceLock both held.
322     */
323    status_t internalPauseAndWaitLocked();
324
325    /**
326     * Resume work after internalPauseAndWaitLocked()
327     * Must be called with mLock and mInterfaceLock both held.
328     */
329    status_t internalResumeLocked();
330
331    /**
332     * Wait until status tracker tells us we've transitioned to the target state
333     * set, which is either ACTIVE when active==true or IDLE (which is any
334     * non-ACTIVE state) when active==false.
335     *
336     * Needs to be called with mLock and mInterfaceLock held.  This means there
337     * can ever only be one waiter at most.
338     *
339     * During the wait mLock is released.
340     *
341     */
342    status_t waitUntilStateThenRelock(bool active, nsecs_t timeout);
343
344    /**
345     * Implementation of waitUntilDrained. On success, will transition to IDLE state.
346     *
347     * Need to be called with mLock and mInterfaceLock held.
348     */
349    status_t waitUntilDrainedLocked();
350
351    /**
352     * Do common work for setting up a streaming or single capture request.
353     * On success, will transition to ACTIVE if in IDLE.
354     */
355    sp<CaptureRequest> setUpRequestLocked(const CameraMetadata &request);
356
357    /**
358     * Build a CaptureRequest request from the CameraDeviceBase request
359     * settings.
360     */
361    sp<CaptureRequest> createCaptureRequest(const CameraMetadata &request);
362
363    /**
364     * Take the currently-defined set of streams and configure the HAL to use
365     * them. This is a long-running operation (may be several hundered ms).
366     */
367    status_t           configureStreamsLocked();
368
369    /**
370     * Add a dummy stream to the current stream set as a workaround for
371     * not allowing 0 streams in the camera HAL spec.
372     */
373    status_t           addDummyStreamLocked();
374
375    /**
376     * Remove a dummy stream if the current config includes real streams.
377     */
378    status_t           tryRemoveDummyStreamLocked();
379
380    /**
381     * Set device into an error state due to some fatal failure, and set an
382     * error message to indicate why. Only the first call's message will be
383     * used. The message is also sent to the log.
384     */
385    void               setErrorState(const char *fmt, ...);
386    void               setErrorStateV(const char *fmt, va_list args);
387    void               setErrorStateLocked(const char *fmt, ...);
388    void               setErrorStateLockedV(const char *fmt, va_list args);
389
390    /**
391     * Debugging trylock/spin method
392     * Try to acquire a lock a few times with sleeps between before giving up.
393     */
394    bool               tryLockSpinRightRound(Mutex& lock);
395
396    /**
397     * Helper function to determine if an input size for implementation defined
398     * format is supported.
399     */
400    bool isOpaqueInputSizeSupported(uint32_t width, uint32_t height);
401
402    /**
403     * Helper function to get the largest Jpeg resolution (in area)
404     * Return Size(0, 0) if static metatdata is invalid
405     */
406    Size getMaxJpegResolution() const;
407
408    /**
409     * Helper function to get the offset between MONOTONIC and BOOTTIME
410     * timestamp.
411     */
412    static nsecs_t getMonoToBoottimeOffset();
413
414    /**
415     * Helper function to map between legacy and new dataspace enums
416     */
417    static android_dataspace mapToLegacyDataspace(android_dataspace dataSpace);
418
419    struct RequestTrigger {
420        // Metadata tag number, e.g. android.control.aePrecaptureTrigger
421        uint32_t metadataTag;
422        // Metadata value, e.g. 'START' or the trigger ID
423        int32_t entryValue;
424
425        // The last part of the fully qualified path, e.g. afTrigger
426        const char *getTagName() const {
427            return get_camera_metadata_tag_name(metadataTag) ?: "NULL";
428        }
429
430        // e.g. TYPE_BYTE, TYPE_INT32, etc.
431        int getTagType() const {
432            return get_camera_metadata_tag_type(metadataTag);
433        }
434    };
435
436    /**
437     * Thread for managing capture request submission to HAL device.
438     */
439    class RequestThread : public Thread {
440
441      public:
442
443        RequestThread(wp<Camera3Device> parent,
444                sp<camera3::StatusTracker> statusTracker,
445                camera3_device_t *hal3Device,
446                bool aeLockAvailable);
447
448        void     setNotificationListener(NotificationListener *listener);
449
450        /**
451         * Call after stream (re)-configuration is completed.
452         */
453        void     configurationComplete();
454
455        /**
456         * Set or clear the list of repeating requests. Does not block
457         * on either. Use waitUntilPaused to wait until request queue
458         * has emptied out.
459         */
460        status_t setRepeatingRequests(const RequestList& requests,
461                                      /*out*/
462                                      int64_t *lastFrameNumber = NULL);
463        status_t clearRepeatingRequests(/*out*/
464                                        int64_t *lastFrameNumber = NULL);
465
466        status_t queueRequestList(List<sp<CaptureRequest> > &requests,
467                                  /*out*/
468                                  int64_t *lastFrameNumber = NULL);
469
470        /**
471         * Remove all queued and repeating requests, and pending triggers
472         */
473        status_t clear(NotificationListener *listener,
474                       /*out*/
475                       int64_t *lastFrameNumber = NULL);
476
477        /**
478         * Flush all pending requests in HAL.
479         */
480        status_t flush();
481
482        /**
483         * Queue a trigger to be dispatched with the next outgoing
484         * process_capture_request. The settings for that request only
485         * will be temporarily rewritten to add the trigger tag/value.
486         * Subsequent requests will not be rewritten (for this tag).
487         */
488        status_t queueTrigger(RequestTrigger trigger[], size_t count);
489
490        /**
491         * Pause/unpause the capture thread. Doesn't block, so use
492         * waitUntilPaused to wait until the thread is paused.
493         */
494        void     setPaused(bool paused);
495
496        /**
497         * Wait until thread processes the capture request with settings'
498         * android.request.id == requestId.
499         *
500         * Returns TIMED_OUT in case the thread does not process the request
501         * within the timeout.
502         */
503        status_t waitUntilRequestProcessed(int32_t requestId, nsecs_t timeout);
504
505        /**
506         * Shut down the thread. Shutdown is asynchronous, so thread may
507         * still be running once this method returns.
508         */
509        virtual void requestExit();
510
511        /**
512         * Get the latest request that was sent to the HAL
513         * with process_capture_request.
514         */
515        CameraMetadata getLatestRequest() const;
516
517        /**
518         * Returns true if the stream is a target of any queued or repeating
519         * capture request
520         */
521        bool isStreamPending(sp<camera3::Camera3StreamInterface>& stream);
522
523      protected:
524
525        virtual bool threadLoop();
526
527      private:
528        static int         getId(const wp<Camera3Device> &device);
529
530        status_t           queueTriggerLocked(RequestTrigger trigger);
531        // Mix-in queued triggers into this request
532        int32_t            insertTriggers(const sp<CaptureRequest> &request);
533        // Purge the queued triggers from this request,
534        //  restoring the old field values for those tags.
535        status_t           removeTriggers(const sp<CaptureRequest> &request);
536
537        // HAL workaround: Make sure a trigger ID always exists if
538        // a trigger does
539        status_t          addDummyTriggerIds(const sp<CaptureRequest> &request);
540
541        static const nsecs_t kRequestTimeout = 50e6; // 50 ms
542
543        // Used to prepare a batch of requests.
544        struct NextRequest {
545            sp<CaptureRequest>              captureRequest;
546            camera3_capture_request_t       halRequest;
547            Vector<camera3_stream_buffer_t> outputBuffers;
548            bool                            submitted;
549        };
550
551        // Wait for the next batch of requests and put them in mNextRequests. mNextRequests will
552        // be empty if it times out.
553        void waitForNextRequestBatch();
554
555        // Waits for a request, or returns NULL if times out. Must be called with mRequestLock hold.
556        sp<CaptureRequest> waitForNextRequestLocked();
557
558        // Prepare HAL requests and output buffers in mNextRequests. Return TIMED_OUT if getting any
559        // output buffer timed out. If an error is returned, the caller should clean up the pending
560        // request batch.
561        status_t prepareHalRequests();
562
563        // Return buffers, etc, for requests in mNextRequests that couldn't be fully constructed and
564        // send request errors if sendRequestError is true. The buffers will be returned in the
565        // ERROR state to mark them as not having valid data. mNextRequests will be cleared.
566        void cleanUpFailedRequests(bool sendRequestError);
567
568        // Pause handling
569        bool               waitIfPaused();
570        void               unpauseForNewRequests();
571
572        // Relay error to parent device object setErrorState
573        void               setErrorState(const char *fmt, ...);
574
575        // If the input request is in mRepeatingRequests. Must be called with mRequestLock hold
576        bool isRepeatingRequestLocked(const sp<CaptureRequest>);
577
578        // Handle AE precapture trigger cancel for devices <= CAMERA_DEVICE_API_VERSION_3_2.
579        void handleAePrecaptureCancelRequest(sp<CaptureRequest> request);
580
581        wp<Camera3Device>  mParent;
582        wp<camera3::StatusTracker>  mStatusTracker;
583        camera3_device_t  *mHal3Device;
584
585        NotificationListener *mListener;
586
587        const int          mId;       // The camera ID
588        int                mStatusId; // The RequestThread's component ID for
589                                      // status tracking
590
591        Mutex              mRequestLock;
592        Condition          mRequestSignal;
593        RequestList        mRequestQueue;
594        RequestList        mRepeatingRequests;
595        // The next batch of requests being prepped for submission to the HAL, no longer
596        // on the request queue. Read-only even with mRequestLock held, outside
597        // of threadLoop
598        Vector<NextRequest> mNextRequests;
599
600        // To protect flush() and sending a request batch to HAL.
601        Mutex              mFlushLock;
602
603        bool               mReconfigured;
604
605        // Used by waitIfPaused, waitForNextRequest, and waitUntilPaused
606        Mutex              mPauseLock;
607        bool               mDoPause;
608        Condition          mDoPauseSignal;
609        bool               mPaused;
610        Condition          mPausedSignal;
611
612        sp<CaptureRequest> mPrevRequest;
613        int32_t            mPrevTriggers;
614
615        uint32_t           mFrameNumber;
616
617        mutable Mutex      mLatestRequestMutex;
618        Condition          mLatestRequestSignal;
619        // android.request.id for latest process_capture_request
620        int32_t            mLatestRequestId;
621        CameraMetadata     mLatestRequest;
622
623        typedef KeyedVector<uint32_t/*tag*/, RequestTrigger> TriggerMap;
624        Mutex              mTriggerMutex;
625        TriggerMap         mTriggerMap;
626        TriggerMap         mTriggerRemovedMap;
627        TriggerMap         mTriggerReplacedMap;
628        uint32_t           mCurrentAfTriggerId;
629        uint32_t           mCurrentPreCaptureTriggerId;
630
631        int64_t            mRepeatingLastFrameNumber;
632
633        // Whether the device supports AE lock
634        bool               mAeLockAvailable;
635    };
636    sp<RequestThread> mRequestThread;
637
638    /**
639     * In-flight queue for tracking completion of capture requests.
640     */
641
642    struct InFlightRequest {
643        // Set by notify() SHUTTER call.
644        nsecs_t shutterTimestamp;
645        // Set by process_capture_result().
646        nsecs_t sensorTimestamp;
647        int     requestStatus;
648        // Set by process_capture_result call with valid metadata
649        bool    haveResultMetadata;
650        // Decremented by calls to process_capture_result with valid output
651        // and input buffers
652        int     numBuffersLeft;
653        CaptureResultExtras resultExtras;
654        // If this request has any input buffer
655        bool hasInputBuffer;
656
657        // The last metadata that framework receives from HAL and
658        // not yet send out because the shutter event hasn't arrived.
659        // It's added by process_capture_result and sent when framework
660        // receives the shutter event.
661        CameraMetadata pendingMetadata;
662
663        // The metadata of the partial results that framework receives from HAL so far
664        // and has sent out.
665        CameraMetadata collectedPartialResult;
666
667        // Buffers are added by process_capture_result when output buffers
668        // return from HAL but framework has not yet received the shutter
669        // event. They will be returned to the streams when framework receives
670        // the shutter event.
671        Vector<camera3_stream_buffer_t> pendingOutputBuffers;
672
673        // Used to cancel AE precapture trigger for devices doesn't support
674        // CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL
675        AeTriggerCancelOverride_t aeTriggerCancelOverride;
676
677        // Default constructor needed by KeyedVector
678        InFlightRequest() :
679                shutterTimestamp(0),
680                sensorTimestamp(0),
681                requestStatus(OK),
682                haveResultMetadata(false),
683                numBuffersLeft(0),
684                hasInputBuffer(false),
685                aeTriggerCancelOverride({false, 0, false, 0}){
686        }
687
688        InFlightRequest(int numBuffers, CaptureResultExtras extras, bool hasInput,
689                AeTriggerCancelOverride aeTriggerCancelOverride) :
690                shutterTimestamp(0),
691                sensorTimestamp(0),
692                requestStatus(OK),
693                haveResultMetadata(false),
694                numBuffersLeft(numBuffers),
695                resultExtras(extras),
696                hasInputBuffer(hasInput),
697                aeTriggerCancelOverride(aeTriggerCancelOverride){
698        }
699    };
700
701    // Map from frame number to the in-flight request state
702    typedef KeyedVector<uint32_t, InFlightRequest> InFlightMap;
703
704    Mutex                  mInFlightLock; // Protects mInFlightMap
705    InFlightMap            mInFlightMap;
706
707    status_t registerInFlight(uint32_t frameNumber,
708            int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
709            const AeTriggerCancelOverride_t &aeTriggerCancelOverride);
710
711    /**
712     * Override result metadata for cancelling AE precapture trigger applied in
713     * handleAePrecaptureCancelRequest().
714     */
715    void overrideResultForPrecaptureCancel(CameraMetadata* result,
716            const AeTriggerCancelOverride_t &aeTriggerCancelOverride);
717
718    /**
719     * Tracking for idle detection
720     */
721    sp<camera3::StatusTracker> mStatusTracker;
722
723    /**
724     * Graphic buffer manager for output streams. Each device has a buffer manager, which is used
725     * by the output streams to get and return buffers if these streams are registered to this
726     * buffer manager.
727     */
728    sp<camera3::Camera3BufferManager> mBufferManager;
729
730    /**
731     * Thread for preparing streams
732     */
733    class PreparerThread : private Thread, public virtual RefBase {
734      public:
735        PreparerThread();
736        ~PreparerThread();
737
738        void setNotificationListener(NotificationListener *listener);
739
740        /**
741         * Queue up a stream to be prepared. Streams are processed by a background thread in FIFO
742         * order.  Pre-allocate up to maxCount buffers for the stream, or the maximum number needed
743         * for the pipeline if maxCount is ALLOCATE_PIPELINE_MAX.
744         */
745        status_t prepare(int maxCount, sp<camera3::Camera3StreamInterface>& stream);
746
747        /**
748         * Cancel all current and pending stream preparation
749         */
750        status_t clear();
751
752      private:
753        Mutex mLock;
754
755        virtual bool threadLoop();
756
757        // Guarded by mLock
758
759        NotificationListener *mListener;
760        List<sp<camera3::Camera3StreamInterface> > mPendingStreams;
761        bool mActive;
762        bool mCancelNow;
763
764        // Only accessed by threadLoop and the destructor
765
766        sp<camera3::Camera3StreamInterface> mCurrentStream;
767    };
768    sp<PreparerThread> mPreparerThread;
769
770    /**
771     * Output result queue and current HAL device 3A state
772     */
773
774    // Lock for output side of device
775    Mutex                  mOutputLock;
776
777    /**** Scope for mOutputLock ****/
778    // the minimal frame number of the next non-reprocess result
779    uint32_t               mNextResultFrameNumber;
780    // the minimal frame number of the next reprocess result
781    uint32_t               mNextReprocessResultFrameNumber;
782    // the minimal frame number of the next non-reprocess shutter
783    uint32_t               mNextShutterFrameNumber;
784    // the minimal frame number of the next reprocess shutter
785    uint32_t               mNextReprocessShutterFrameNumber;
786    List<CaptureResult>   mResultQueue;
787    Condition              mResultSignal;
788    NotificationListener  *mListener;
789
790    /**** End scope for mOutputLock ****/
791
792    /**
793     * Callback functions from HAL device
794     */
795    void processCaptureResult(const camera3_capture_result *result);
796
797    void notify(const camera3_notify_msg *msg);
798
799    // Specific notify handlers
800    void notifyError(const camera3_error_msg_t &msg,
801            NotificationListener *listener);
802    void notifyShutter(const camera3_shutter_msg_t &msg,
803            NotificationListener *listener);
804
805    // helper function to return the output buffers to the streams.
806    void returnOutputBuffers(const camera3_stream_buffer_t *outputBuffers,
807            size_t numBuffers, nsecs_t timestamp);
808
809    // Send a partial capture result.
810    void sendPartialCaptureResult(const camera_metadata_t * partialResult,
811            const CaptureResultExtras &resultExtras, uint32_t frameNumber,
812            const AeTriggerCancelOverride_t &aeTriggerCancelOverride);
813
814    // Send a total capture result given the pending metadata and result extras,
815    // partial results, and the frame number to the result queue.
816    void sendCaptureResult(CameraMetadata &pendingMetadata,
817            CaptureResultExtras &resultExtras,
818            CameraMetadata &collectedPartialResult, uint32_t frameNumber,
819            bool reprocess, const AeTriggerCancelOverride_t &aeTriggerCancelOverride);
820
821    // Insert the result to the result queue after updating frame number and overriding AE
822    // trigger cancel.
823    // mOutputLock must be held when calling this function.
824    void insertResultLocked(CaptureResult *result, uint32_t frameNumber,
825            const AeTriggerCancelOverride_t &aeTriggerCancelOverride);
826
827    /**** Scope for mInFlightLock ****/
828
829    // Remove the in-flight request of the given index from mInFlightMap
830    // if it's no longer needed. It must only be called with mInFlightLock held.
831    void removeInFlightRequestIfReadyLocked(int idx);
832
833    /**** End scope for mInFlightLock ****/
834
835    /**
836     * Static callback forwarding methods from HAL to instance
837     */
838    static callbacks_process_capture_result_t sProcessCaptureResult;
839
840    static callbacks_notify_t sNotify;
841
842}; // class Camera3Device
843
844}; // namespace android
845
846#endif
847