ConsumerBase.cpp revision 1585c4d9fbbba3ba70ae625923b85cd02cb8a0fd
1/*
2 * Copyright (C) 2010 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#define LOG_TAG "ConsumerBase"
18#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19//#define LOG_NDEBUG 0
20
21#define EGL_EGLEXT_PROTOTYPES
22
23#include <EGL/egl.h>
24#include <EGL/eglext.h>
25
26#include <hardware/hardware.h>
27
28#include <gui/IGraphicBufferAlloc.h>
29#include <gui/ISurfaceComposer.h>
30#include <gui/SurfaceComposerClient.h>
31#include <gui/ConsumerBase.h>
32
33#include <private/gui/ComposerService.h>
34
35#include <utils/Log.h>
36#include <utils/String8.h>
37#include <utils/Trace.h>
38
39// Macros for including the ConsumerBase name in log messages
40#define CB_LOGV(x, ...) ALOGV("[%s] "x, mName.string(), ##__VA_ARGS__)
41#define CB_LOGD(x, ...) ALOGD("[%s] "x, mName.string(), ##__VA_ARGS__)
42#define CB_LOGI(x, ...) ALOGI("[%s] "x, mName.string(), ##__VA_ARGS__)
43#define CB_LOGW(x, ...) ALOGW("[%s] "x, mName.string(), ##__VA_ARGS__)
44#define CB_LOGE(x, ...) ALOGE("[%s] "x, mName.string(), ##__VA_ARGS__)
45
46namespace android {
47
48// Get an ID that's unique within this process.
49static int32_t createProcessUniqueId() {
50    static volatile int32_t globalCounter = 0;
51    return android_atomic_inc(&globalCounter);
52}
53
54ConsumerBase::ConsumerBase(const sp<BufferQueue>& bufferQueue) :
55        mAbandoned(false),
56        mBufferQueue(bufferQueue) {
57    // Choose a name using the PID and a process-unique ID.
58    mName = String8::format("unnamed-%d-%d", getpid(), createProcessUniqueId());
59
60    // Note that we can't create an sp<...>(this) in a ctor that will not keep a
61    // reference once the ctor ends, as that would cause the refcount of 'this'
62    // dropping to 0 at the end of the ctor.  Since all we need is a wp<...>
63    // that's what we create.
64    wp<BufferQueue::ConsumerListener> listener;
65    sp<BufferQueue::ConsumerListener> proxy;
66    listener = static_cast<BufferQueue::ConsumerListener*>(this);
67    proxy = new BufferQueue::ProxyConsumerListener(listener);
68
69    status_t err = mBufferQueue->consumerConnect(proxy);
70    if (err != NO_ERROR) {
71        CB_LOGE("ConsumerBase: error connecting to BufferQueue: %s (%d)",
72                strerror(-err), err);
73    } else {
74        mBufferQueue->setConsumerName(mName);
75    }
76}
77
78ConsumerBase::~ConsumerBase() {
79    CB_LOGV("~ConsumerBase");
80    Mutex::Autolock lock(mMutex);
81
82    // Verify that abandon() has been called before we get here.  This should
83    // be done by ConsumerBase::onLastStrongRef(), but it's possible for a
84    // derived class to override that method and not call
85    // ConsumerBase::onLastStrongRef().
86    LOG_ALWAYS_FATAL_IF(!mAbandoned, "[%s] ~ConsumerBase was called, but the "
87        "consumer is not abandoned!", mName.string());
88}
89
90void ConsumerBase::onLastStrongRef(const void* id) {
91    abandon();
92}
93
94void ConsumerBase::freeBufferLocked(int slotIndex) {
95    CB_LOGV("freeBufferLocked: slotIndex=%d", slotIndex);
96    mSlots[slotIndex].mGraphicBuffer = 0;
97    mSlots[slotIndex].mFence = Fence::NO_FENCE;
98    mSlots[slotIndex].mFrameNumber = 0;
99}
100
101// Used for refactoring, should not be in final interface
102sp<BufferQueue> ConsumerBase::getBufferQueue() const {
103    Mutex::Autolock lock(mMutex);
104    return mBufferQueue;
105}
106
107void ConsumerBase::onFrameAvailable() {
108    CB_LOGV("onFrameAvailable");
109
110    sp<FrameAvailableListener> listener;
111    { // scope for the lock
112        Mutex::Autolock lock(mMutex);
113        listener = mFrameAvailableListener.promote();
114    }
115
116    if (listener != NULL) {
117        CB_LOGV("actually calling onFrameAvailable");
118        listener->onFrameAvailable();
119    }
120}
121
122void ConsumerBase::onBuffersReleased() {
123    Mutex::Autolock lock(mMutex);
124
125    CB_LOGV("onBuffersReleased");
126
127    if (mAbandoned) {
128        // Nothing to do if we're already abandoned.
129        return;
130    }
131
132    uint32_t mask = 0;
133    mBufferQueue->getReleasedBuffers(&mask);
134    for (int i = 0; i < BufferQueue::NUM_BUFFER_SLOTS; i++) {
135        if (mask & (1 << i)) {
136            freeBufferLocked(i);
137        }
138    }
139}
140
141void ConsumerBase::abandon() {
142    CB_LOGV("abandon");
143    Mutex::Autolock lock(mMutex);
144
145    if (!mAbandoned) {
146        abandonLocked();
147        mAbandoned = true;
148    }
149}
150
151void ConsumerBase::abandonLocked() {
152	CB_LOGV("abandonLocked");
153    for (int i =0; i < BufferQueue::NUM_BUFFER_SLOTS; i++) {
154        freeBufferLocked(i);
155    }
156    // disconnect from the BufferQueue
157    mBufferQueue->consumerDisconnect();
158    mBufferQueue.clear();
159}
160
161void ConsumerBase::setFrameAvailableListener(
162        const wp<FrameAvailableListener>& listener) {
163    CB_LOGV("setFrameAvailableListener");
164    Mutex::Autolock lock(mMutex);
165    mFrameAvailableListener = listener;
166}
167
168void ConsumerBase::dump(String8& result) const {
169    dump(result, "");
170}
171
172void ConsumerBase::dump(String8& result, const char* prefix) const {
173    Mutex::Autolock _l(mMutex);
174    dumpLocked(result, prefix);
175}
176
177void ConsumerBase::dumpLocked(String8& result, const char* prefix) const {
178    result.appendFormat("%smAbandoned=%d\n", prefix, int(mAbandoned));
179
180    if (!mAbandoned) {
181        mBufferQueue->dump(result, prefix);
182    }
183}
184
185status_t ConsumerBase::acquireBufferLocked(BufferQueue::BufferItem *item,
186        nsecs_t presentWhen) {
187    status_t err = mBufferQueue->acquireBuffer(item, presentWhen);
188    if (err != NO_ERROR) {
189        return err;
190    }
191
192    if (item->mGraphicBuffer != NULL) {
193        mSlots[item->mBuf].mGraphicBuffer = item->mGraphicBuffer;
194    }
195
196    mSlots[item->mBuf].mFrameNumber = item->mFrameNumber;
197    mSlots[item->mBuf].mFence = item->mFence;
198
199    CB_LOGV("acquireBufferLocked: -> slot=%d/%llu",
200            item->mBuf, item->mFrameNumber);
201
202    return OK;
203}
204
205status_t ConsumerBase::addReleaseFence(int slot,
206        const sp<GraphicBuffer> graphicBuffer, const sp<Fence>& fence) {
207    Mutex::Autolock lock(mMutex);
208    return addReleaseFenceLocked(slot, graphicBuffer, fence);
209}
210
211status_t ConsumerBase::addReleaseFenceLocked(int slot,
212        const sp<GraphicBuffer> graphicBuffer, const sp<Fence>& fence) {
213    CB_LOGV("addReleaseFenceLocked: slot=%d", slot);
214
215    // If consumer no longer tracks this graphicBuffer, we can safely
216    // drop this fence, as it will never be received by the producer.
217    if (!stillTracking(slot, graphicBuffer)) {
218        return OK;
219    }
220
221    if (!mSlots[slot].mFence.get()) {
222        mSlots[slot].mFence = fence;
223    } else {
224        sp<Fence> mergedFence = Fence::merge(
225                String8::format("%.28s:%d", mName.string(), slot),
226                mSlots[slot].mFence, fence);
227        if (!mergedFence.get()) {
228            CB_LOGE("failed to merge release fences");
229            // synchronization is broken, the best we can do is hope fences
230            // signal in order so the new fence will act like a union
231            mSlots[slot].mFence = fence;
232            return BAD_VALUE;
233        }
234        mSlots[slot].mFence = mergedFence;
235    }
236
237    return OK;
238}
239
240status_t ConsumerBase::releaseBufferLocked(
241        int slot, const sp<GraphicBuffer> graphicBuffer,
242        EGLDisplay display, EGLSyncKHR eglFence) {
243    // If consumer no longer tracks this graphicBuffer (we received a new
244    // buffer on the same slot), the buffer producer is definitely no longer
245    // tracking it.
246    if (!stillTracking(slot, graphicBuffer)) {
247        return OK;
248    }
249
250    CB_LOGV("releaseBufferLocked: slot=%d/%llu",
251            slot, mSlots[slot].mFrameNumber);
252    status_t err = mBufferQueue->releaseBuffer(slot, mSlots[slot].mFrameNumber,
253            display, eglFence, mSlots[slot].mFence);
254    if (err == BufferQueue::STALE_BUFFER_SLOT) {
255        freeBufferLocked(slot);
256    }
257
258    mSlots[slot].mFence = Fence::NO_FENCE;
259
260    return err;
261}
262
263bool ConsumerBase::stillTracking(int slot,
264        const sp<GraphicBuffer> graphicBuffer) {
265    if (slot < 0 || slot >= BufferQueue::NUM_BUFFER_SLOTS) {
266        return false;
267    }
268    return (mSlots[slot].mGraphicBuffer != NULL &&
269            mSlots[slot].mGraphicBuffer->handle == graphicBuffer->handle);
270}
271
272} // namespace android
273