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