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_GUI_RINGBUFFERCONSUMER_H
18 #define ANDROID_GUI_RINGBUFFERCONSUMER_H
19 
20 #include <gui/BufferItem.h>
21 #include <gui/ConsumerBase.h>
22 #include <gui/BufferQueue.h>
23 
24 #include <utils/List.h>
25 
26 #define ANDROID_GRAPHICS_RINGBUFFERCONSUMER_JNI_ID "mRingBufferConsumer"
27 
28 namespace android {
29 
30 /**
31  * The RingBufferConsumer maintains a ring buffer of BufferItem objects,
32  * (which are 'acquired' as long as they are part of the ring buffer, and
33  *  'released' when they leave the ring buffer).
34  *
35  * When new buffers are produced, the oldest non-pinned buffer item is immediately
36  * dropped from the ring buffer, and overridden with the newest buffer.
37  *
38  * Users can only access a buffer item after pinning it (which also guarantees
39  * that during its duration it will not be released back into the BufferQueue).
40  *
41  * Note that the 'oldest' buffer is the one with the smallest timestamp.
42  *
43  * Edge cases:
44  *  - If ringbuffer is not full, no drops occur when a buffer is produced.
45  *  - If all the buffers get filled or pinned then there will be no empty
46  *    buffers left, so the producer will block on dequeue.
47  */
48 class RingBufferConsumer : public ConsumerBase,
49                            public ConsumerBase::FrameAvailableListener
50 {
51   public:
52     typedef ConsumerBase::FrameAvailableListener FrameAvailableListener;
53 
54     enum { INVALID_BUFFER_SLOT = BufferQueue::INVALID_BUFFER_SLOT };
55     enum { NO_BUFFER_AVAILABLE = BufferQueue::NO_BUFFER_AVAILABLE };
56 
57     // Create a new ring buffer consumer. The consumerUsage parameter determines
58     // the consumer usage flags passed to the graphics allocator. The
59     // bufferCount parameter specifies how many buffers can be pinned for user
60     // access at the same time.
61     RingBufferConsumer(const sp<IGraphicBufferConsumer>& consumer, uint64_t consumerUsage,
62             int bufferCount);
63 
64     virtual ~RingBufferConsumer();
65 
66     // set the name of the RingBufferConsumer that will be used to identify it in
67     // log messages.
68     void setName(const std::string& name);
69 
70     // setDefaultBufferSize is used to set the size of buffers returned by
71     // requestBuffers when a with and height of zero is requested.
72     status_t setDefaultBufferSize(uint32_t w, uint32_t h);
73 
74     // setDefaultBufferFormat allows the BufferQueue to create
75     // GraphicBuffers of a defaultFormat if no format is specified
76     // by the producer endpoint.
77     status_t setDefaultBufferFormat(uint32_t defaultFormat);
78 
79     // setConsumerUsage allows the BufferQueue consumer usage to be
80     // set at a later time after construction.
81     status_t setConsumerUsage(uint64_t usage);
82 
83     // Buffer info, minus the graphics buffer/slot itself.
84     struct BufferInfo {
85         // mCrop is the current crop rectangle for this buffer slot.
86         Rect mCrop;
87 
88         // mTransform is the current transform flags for this buffer slot.
89         uint32_t mTransform;
90 
91         // mScalingMode is the current scaling mode for this buffer slot.
92         uint32_t mScalingMode;
93 
94         // mTimestamp is the current timestamp for this buffer slot. This gets
95         // to set by queueBuffer each time this slot is queued.
96         int64_t mTimestamp;
97 
98         // mFrameNumber is the number of the queued frame for this slot.
99         uint64_t mFrameNumber;
100 
101         // mPinned is whether or not the buffer has been pinned already.
102         bool mPinned;
103     };
104 
105     struct RingBufferComparator {
106         // Return < 0 to select i1, > 0 to select i2, 0 for neither
107         // i1 or i2 can be NULL.
108         //
109         // The comparator has to implement a total ordering. Otherwise
110         // a linear scan won't find the most preferred buffer.
111         virtual int compare(const BufferInfo* i1,
112                             const BufferInfo* i2) const = 0;
113 
~RingBufferComparatorRingBufferComparator114         virtual ~RingBufferComparator() {}
115     };
116 
117     struct PinnedBufferItem : public LightRefBase<PinnedBufferItem> {
PinnedBufferItemPinnedBufferItem118         PinnedBufferItem(wp<RingBufferConsumer> consumer,
119                          const BufferItem& item) :
120                 mConsumer(consumer),
121                 mBufferItem(item) {
122         }
123 
~PinnedBufferItemPinnedBufferItem124         ~PinnedBufferItem() {
125             sp<RingBufferConsumer> consumer = mConsumer.promote();
126             if (consumer != NULL) {
127                 consumer->unpinBuffer(mBufferItem);
128             }
129         }
130 
isEmptyPinnedBufferItem131         bool isEmpty() {
132             return mBufferItem.mSlot == BufferQueue::INVALID_BUFFER_SLOT;
133         }
134 
getBufferItemPinnedBufferItem135         BufferItem& getBufferItem() { return mBufferItem; }
getBufferItemPinnedBufferItem136         const BufferItem& getBufferItem() const { return mBufferItem; }
137 
138       private:
139         wp<RingBufferConsumer> mConsumer;
140         BufferItem             mBufferItem;
141     };
142 
143     // Find a buffer using the filter, then pin it before returning it.
144     //
145     // The filter will be invoked on each buffer item in the ring buffer,
146     // passing the item that was selected from each previous iteration,
147     // as well as the current iteration's item.
148     //
149     // Pinning will ensure that the buffer will not be dropped when a new
150     // frame is available.
151     sp<PinnedBufferItem> pinSelectedBuffer(const RingBufferComparator& filter,
152                                            bool waitForFence = true);
153 
154     // Release all the non-pinned buffers in the ring buffer
155     status_t clear();
156 
157     // Return 0 if RingBuffer is empty, otherwise return timestamp of latest buffer.
158     nsecs_t getLatestTimestamp();
159 
160   private:
161 
162     // Override ConsumerBase::onFrameAvailable
163     virtual void onFrameAvailable(const BufferItem& item);
164 
165     void pinBufferLocked(const BufferItem& item);
166     void unpinBuffer(const BufferItem& item);
167 
168     // Releases oldest buffer. Returns NO_BUFFER_AVAILABLE
169     // if all the buffers were pinned.
170     // Returns NOT_ENOUGH_DATA if list was empty.
171     status_t releaseOldestBufferLocked(size_t* pinnedFrames);
172 
173     struct RingBufferItem : public BufferItem {
RingBufferItemRingBufferItem174         RingBufferItem() : BufferItem(), mPinCount(0) {}
175         int mPinCount;
176     };
177 
178     // List of acquired buffers in our ring buffer
179     List<RingBufferItem>       mBufferItemList;
180     const int                  mBufferCount;
181 
182     // Timestamp of latest buffer
183     nsecs_t mLatestTimestamp;
184 };
185 
186 } // namespace android
187 
188 #endif // ANDROID_GUI_RINGBUFFERCONSUMER_H
189