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