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