Home | History | Annotate | Download | only in device3
      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_CAMERA3_STREAM_H
     18 #define ANDROID_SERVERS_CAMERA3_STREAM_H
     19 
     20 #include <gui/Surface.h>
     21 #include <utils/RefBase.h>
     22 #include <utils/String8.h>
     23 #include <utils/String16.h>
     24 #include <utils/List.h>
     25 
     26 #include "hardware/camera3.h"
     27 
     28 #include "Camera3StreamBufferListener.h"
     29 #include "Camera3StreamInterface.h"
     30 
     31 namespace android {
     32 
     33 namespace camera3 {
     34 
     35 /**
     36  * A class for managing a single stream of input or output data from the camera
     37  * device.
     38  *
     39  * The stream has an internal state machine to track whether it's
     40  * connected/configured/etc.
     41  *
     42  * States:
     43  *
     44  *  STATE_ERROR: A serious error has occurred, stream is unusable. Outstanding
     45  *    buffers may still be returned.
     46  *
     47  *  STATE_CONSTRUCTED: The stream is ready for configuration, but buffers cannot
     48  *    be gotten yet. Not connected to any endpoint, no buffers are registered
     49  *    with the HAL.
     50  *
     51  *  STATE_IN_CONFIG: Configuration has started, but not yet concluded. During this
     52  *    time, the usage, max_buffers, and priv fields of camera3_stream returned by
     53  *    startConfiguration() may be modified.
     54  *
     55  *  STATE_IN_RE_CONFIG: Configuration has started, and the stream has been
     56  *    configured before. Need to track separately from IN_CONFIG to avoid
     57  *    re-registering buffers with HAL.
     58  *
     59  *  STATE_CONFIGURED: Stream is configured, and has registered buffers with the
     60  *    HAL (if necessary). The stream's getBuffer/returnBuffer work. The priv
     61  *    pointer may still be modified.
     62  *
     63  *  STATE_PREPARING: The stream's buffers are being pre-allocated for use.  On
     64  *    older HALs, this is done as part of configuration, but in newer HALs
     65  *    buffers may be allocated at time of first use. But some use cases require
     66  *    buffer allocation upfront, to minmize disruption due to lengthy allocation
     67  *    duration.  In this state, only prepareNextBuffer() and cancelPrepare()
     68  *    may be called.
     69  *
     70  * Transition table:
     71  *
     72  *    <none>               => STATE_CONSTRUCTED:
     73  *        When constructed with valid arguments
     74  *    <none>               => STATE_ERROR:
     75  *        When constructed with invalid arguments
     76  *    STATE_CONSTRUCTED    => STATE_IN_CONFIG:
     77  *        When startConfiguration() is called
     78  *    STATE_IN_CONFIG      => STATE_CONFIGURED:
     79  *        When finishConfiguration() is called
     80  *    STATE_IN_CONFIG      => STATE_ERROR:
     81  *        When finishConfiguration() fails to allocate or register buffers.
     82  *    STATE_CONFIGURED     => STATE_IN_RE_CONFIG:  *
     83  *        When startConfiguration() is called again, after making sure stream is
     84  *        idle with waitUntilIdle().
     85  *    STATE_IN_RE_CONFIG   => STATE_CONFIGURED:
     86  *        When finishConfiguration() is called.
     87  *    STATE_IN_RE_CONFIG   => STATE_ERROR:
     88  *        When finishConfiguration() fails to allocate or register buffers.
     89  *    STATE_CONFIGURED     => STATE_CONSTRUCTED:
     90  *        When disconnect() is called after making sure stream is idle with
     91  *        waitUntilIdle().
     92  *    STATE_CONFIGURED     => STATE_PREPARING:
     93  *        When startPrepare is called before the stream has a buffer
     94  *        queued back into it for the first time.
     95  *    STATE_PREPARING      => STATE_CONFIGURED:
     96  *        When sufficient prepareNextBuffer calls have been made to allocate
     97  *        all stream buffers, or cancelPrepare is called.
     98  *
     99  * Status Tracking:
    100  *    Each stream is tracked by StatusTracker as a separate component,
    101  *    depending on the handed out buffer count. The state must be STATE_CONFIGURED
    102  *    in order for the component to be marked.
    103  *
    104  *    It's marked in one of two ways:
    105  *
    106  *    - ACTIVE: One or more buffers have been handed out (with #getBuffer).
    107  *    - IDLE: All buffers have been returned (with #returnBuffer), and their
    108  *          respective release_fence(s) have been signaled.
    109  *
    110  *    A typical use case is output streams. When the HAL has any buffers
    111  *    dequeued, the stream is marked ACTIVE. When the HAL returns all buffers
    112  *    (e.g. if no capture requests are active), the stream is marked IDLE.
    113  *    In this use case, the app consumer does not affect the component status.
    114  *
    115  */
    116 class Camera3Stream :
    117         protected camera3_stream,
    118         public virtual Camera3StreamInterface,
    119         public virtual RefBase {
    120   public:
    121 
    122     virtual ~Camera3Stream();
    123 
    124     static Camera3Stream*       cast(camera3_stream *stream);
    125     static const Camera3Stream* cast(const camera3_stream *stream);
    126 
    127     /**
    128      * Get the stream's ID
    129      */
    130     int              getId() const;
    131 
    132     /**
    133      * Get the stream's dimensions and format
    134      */
    135     uint32_t          getWidth() const;
    136     uint32_t          getHeight() const;
    137     int               getFormat() const;
    138     android_dataspace getDataSpace() const;
    139 
    140     /**
    141      * Start the stream configuration process. Returns a handle to the stream's
    142      * information to be passed into the HAL device's configure_streams call.
    143      *
    144      * Until finishConfiguration() is called, no other methods on the stream may be
    145      * called. The usage and max_buffers fields of camera3_stream may be modified
    146      * between start/finishConfiguration, but may not be changed after that.
    147      * The priv field of camera3_stream may be modified at any time after
    148      * startConfiguration.
    149      *
    150      * Returns NULL in case of error starting configuration.
    151      */
    152     camera3_stream*  startConfiguration();
    153 
    154     /**
    155      * Check if the stream is mid-configuration (start has been called, but not
    156      * finish).  Used for lazy completion of configuration.
    157      */
    158     bool             isConfiguring() const;
    159 
    160     /**
    161      * Completes the stream configuration process. During this call, the stream
    162      * may call the device's register_stream_buffers() method. The stream
    163      * information structure returned by startConfiguration() may no longer be
    164      * modified after this call, but can still be read until the destruction of
    165      * the stream.
    166      *
    167      * Returns:
    168      *   OK on a successful configuration
    169      *   NO_INIT in case of a serious error from the HAL device
    170      *   NO_MEMORY in case of an error registering buffers
    171      *   INVALID_OPERATION in case connecting to the consumer failed
    172      */
    173     status_t         finishConfiguration(camera3_device *hal3Device);
    174 
    175     /**
    176      * Cancels the stream configuration process. This returns the stream to the
    177      * initial state, allowing it to be configured again later.
    178      * This is done if the HAL rejects the proposed combined stream configuration
    179      */
    180     status_t         cancelConfiguration();
    181 
    182     /**
    183      * Determine whether the stream has already become in-use (has received
    184      * a valid filled buffer), which determines if a stream can still have
    185      * prepareNextBuffer called on it.
    186      */
    187     bool             isUnpreparable();
    188 
    189     /**
    190      * Start stream preparation. May only be called in the CONFIGURED state,
    191      * when no valid buffers have yet been returned to this stream.
    192      *
    193      * If no prepartion is necessary, returns OK and does not transition to
    194      * PREPARING state. Otherwise, returns NOT_ENOUGH_DATA and transitions
    195      * to PREPARING.
    196      *
    197      * This call performs no allocation, so is quick to call.
    198      *
    199      * Returns:
    200      *    OK if no more buffers need to be preallocated
    201      *    NOT_ENOUGH_DATA if calls to prepareNextBuffer are needed to finish
    202      *        buffer pre-allocation, and transitions to the PREPARING state.
    203      *    NO_INIT in case of a serious error from the HAL device
    204      *    INVALID_OPERATION if called when not in CONFIGURED state, or a
    205      *        valid buffer has already been returned to this stream.
    206      */
    207     status_t         startPrepare();
    208 
    209     /**
    210      * Check if the stream is mid-preparing.
    211      */
    212     bool             isPreparing() const;
    213 
    214     /**
    215      * Continue stream buffer preparation by allocating the next
    216      * buffer for this stream.  May only be called in the PREPARED state.
    217      *
    218      * Returns OK and transitions to the CONFIGURED state if all buffers
    219      * are allocated after the call concludes. Otherwise returns NOT_ENOUGH_DATA.
    220      *
    221      * This call allocates one buffer, which may take several milliseconds for
    222      * large buffers.
    223      *
    224      * Returns:
    225      *    OK if no more buffers need to be preallocated, and transitions
    226      *        to the CONFIGURED state.
    227      *    NOT_ENOUGH_DATA if more calls to prepareNextBuffer are needed to finish
    228      *        buffer pre-allocation.
    229      *    NO_INIT in case of a serious error from the HAL device
    230      *    INVALID_OPERATION if called when not in CONFIGURED state, or a
    231      *        valid buffer has already been returned to this stream.
    232      */
    233     status_t         prepareNextBuffer();
    234 
    235     /**
    236      * Cancel stream preparation early. In case allocation needs to be
    237      * stopped, this method transitions the stream back to the CONFIGURED state.
    238      * Buffers that have been allocated with prepareNextBuffer remain that way,
    239      * but a later use of prepareNextBuffer will require just as many
    240      * calls as if the earlier prepare attempt had not existed.
    241      *
    242      * Returns:
    243      *    OK if cancellation succeeded, and transitions to the CONFIGURED state
    244      *    INVALID_OPERATION if not in the PREPARING state
    245      *    NO_INIT in case of a serious error from the HAL device
    246      */
    247     status_t        cancelPrepare();
    248 
    249     /**
    250      * Tear down memory for this stream. This frees all unused gralloc buffers
    251      * allocated for this stream, but leaves it ready for operation afterward.
    252      *
    253      * May only be called in the CONFIGURED state, and keeps the stream in
    254      * the CONFIGURED state.
    255      *
    256      * Returns:
    257      *    OK if teardown succeeded.
    258      *    INVALID_OPERATION if not in the CONFIGURED state
    259      *    NO_INIT in case of a serious error from the HAL device
    260      */
    261     status_t       tearDown();
    262 
    263     /**
    264      * Fill in the camera3_stream_buffer with the next valid buffer for this
    265      * stream, to hand over to the HAL.
    266      *
    267      * This method may only be called once finishConfiguration has been called.
    268      * For bidirectional streams, this method applies to the output-side
    269      * buffers.
    270      *
    271      */
    272     status_t         getBuffer(camera3_stream_buffer *buffer);
    273 
    274     /**
    275      * Return a buffer to the stream after use by the HAL.
    276      *
    277      * This method may only be called for buffers provided by getBuffer().
    278      * For bidirectional streams, this method applies to the output-side buffers
    279      */
    280     status_t         returnBuffer(const camera3_stream_buffer &buffer,
    281             nsecs_t timestamp);
    282 
    283     /**
    284      * Fill in the camera3_stream_buffer with the next valid buffer for this
    285      * stream, to hand over to the HAL.
    286      *
    287      * This method may only be called once finishConfiguration has been called.
    288      * For bidirectional streams, this method applies to the input-side
    289      * buffers.
    290      *
    291      */
    292     status_t         getInputBuffer(camera3_stream_buffer *buffer);
    293 
    294     /**
    295      * Return a buffer to the stream after use by the HAL.
    296      *
    297      * This method may only be called for buffers provided by getBuffer().
    298      * For bidirectional streams, this method applies to the input-side buffers
    299      */
    300     status_t         returnInputBuffer(const camera3_stream_buffer &buffer);
    301 
    302     // get the buffer producer of the input buffer queue.
    303     // only apply to input streams.
    304     status_t         getInputBufferProducer(sp<IGraphicBufferProducer> *producer);
    305 
    306     /**
    307      * Whether any of the stream's buffers are currently in use by the HAL,
    308      * including buffers that have been returned but not yet had their
    309      * release fence signaled.
    310      */
    311     bool             hasOutstandingBuffers() const;
    312 
    313     enum {
    314         TIMEOUT_NEVER = -1
    315     };
    316 
    317     /**
    318      * Set the status tracker to notify about idle transitions
    319      */
    320     virtual status_t setStatusTracker(sp<StatusTracker> statusTracker);
    321 
    322     /**
    323      * Disconnect stream from its non-HAL endpoint. After this,
    324      * start/finishConfiguration must be called before the stream can be used
    325      * again. This cannot be called if the stream has outstanding dequeued
    326      * buffers.
    327      */
    328     status_t         disconnect();
    329 
    330     /**
    331      * Debug dump of the stream's state.
    332      */
    333     virtual void     dump(int fd, const Vector<String16> &args) const = 0;
    334 
    335     /**
    336      * Add a camera3 buffer listener. Adding the same listener twice has
    337      * no effect.
    338      */
    339     void             addBufferListener(
    340             wp<Camera3StreamBufferListener> listener);
    341 
    342     /**
    343      * Remove a camera3 buffer listener. Removing the same listener twice
    344      * or the listener that was never added has no effect.
    345      */
    346     void             removeBufferListener(
    347             const sp<Camera3StreamBufferListener>& listener);
    348 
    349   protected:
    350     const int mId;
    351     const String8 mName;
    352     // Zero for formats with fixed buffer size for given dimensions.
    353     const size_t mMaxSize;
    354 
    355     enum {
    356         STATE_ERROR,
    357         STATE_CONSTRUCTED,
    358         STATE_IN_CONFIG,
    359         STATE_IN_RECONFIG,
    360         STATE_CONFIGURED,
    361         STATE_PREPARING
    362     } mState;
    363 
    364     mutable Mutex mLock;
    365 
    366     Camera3Stream(int id, camera3_stream_type type,
    367             uint32_t width, uint32_t height, size_t maxSize, int format,
    368             android_dataspace dataSpace, camera3_stream_rotation_t rotation);
    369 
    370     /**
    371      * Interface to be implemented by derived classes
    372      */
    373 
    374     // getBuffer / returnBuffer implementations
    375 
    376     // Since camera3_stream_buffer includes a raw pointer to the stream,
    377     // cast to camera3_stream*, implementations must increment the
    378     // refcount of the stream manually in getBufferLocked, and decrement it in
    379     // returnBufferLocked.
    380     virtual status_t getBufferLocked(camera3_stream_buffer *buffer);
    381     virtual status_t returnBufferLocked(const camera3_stream_buffer &buffer,
    382             nsecs_t timestamp);
    383     virtual status_t getInputBufferLocked(camera3_stream_buffer *buffer);
    384     virtual status_t returnInputBufferLocked(
    385             const camera3_stream_buffer &buffer);
    386     virtual bool     hasOutstandingBuffersLocked() const = 0;
    387     // Get the buffer producer of the input buffer queue. Only apply to input streams.
    388     virtual status_t getInputBufferProducerLocked(sp<IGraphicBufferProducer> *producer);
    389 
    390     // Can return -ENOTCONN when we are already disconnected (not an error)
    391     virtual status_t disconnectLocked() = 0;
    392 
    393     // Configure the buffer queue interface to the other end of the stream,
    394     // after the HAL has provided usage and max_buffers values. After this call,
    395     // the stream must be ready to produce all buffers for registration with
    396     // HAL.
    397     virtual status_t configureQueueLocked() = 0;
    398 
    399     // Get the total number of buffers in the queue
    400     virtual size_t   getBufferCountLocked() = 0;
    401 
    402     // Get handout output buffer count.
    403     virtual size_t   getHandoutOutputBufferCountLocked() = 0;
    404 
    405     // Get handout input buffer count.
    406     virtual size_t   getHandoutInputBufferCountLocked() = 0;
    407 
    408     // Get the usage flags for the other endpoint, or return
    409     // INVALID_OPERATION if they cannot be obtained.
    410     virtual status_t getEndpointUsage(uint32_t *usage) const = 0;
    411 
    412     // Tracking for idle state
    413     wp<StatusTracker> mStatusTracker;
    414     // Status tracker component ID
    415     int mStatusId;
    416 
    417     // Tracking for stream prepare - whether this stream can still have
    418     // prepareNextBuffer called on it.
    419     bool mStreamUnpreparable;
    420 
    421   private:
    422     uint32_t oldUsage;
    423     uint32_t oldMaxBuffers;
    424     Condition mOutputBufferReturnedSignal;
    425     Condition mInputBufferReturnedSignal;
    426     static const nsecs_t kWaitForBufferDuration = 3000000000LL; // 3000 ms
    427 
    428     // Gets all buffers from endpoint and registers them with the HAL.
    429     status_t registerBuffersLocked(camera3_device *hal3Device);
    430 
    431     void fireBufferListenersLocked(const camera3_stream_buffer& buffer,
    432                                   bool acquired, bool output);
    433     List<wp<Camera3StreamBufferListener> > mBufferListenerList;
    434 
    435     status_t        cancelPrepareLocked();
    436 
    437     // Tracking for PREPARING state
    438 
    439     // State of buffer preallocation. Only true if either prepareNextBuffer
    440     // has been called sufficient number of times, or stream configuration
    441     // had to register buffers with the HAL
    442     bool mPrepared;
    443 
    444     Vector<camera3_stream_buffer_t> mPreparedBuffers;
    445     size_t mPreparedBufferIdx;
    446 
    447 }; // class Camera3Stream
    448 
    449 }; // namespace camera3
    450 
    451 }; // namespace android
    452 
    453 #endif
    454