BufferQueueConsumer.cpp revision 9f3053de78630815d60cf48a2cf2348cc5867c45
1/*
2 * Copyright 2014 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 "BufferQueueConsumer"
18#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19//#define LOG_NDEBUG 0
20
21#include <gui/BufferItem.h>
22#include <gui/BufferQueueConsumer.h>
23#include <gui/BufferQueueCore.h>
24#include <gui/IConsumerListener.h>
25
26namespace android {
27
28BufferQueueConsumer::BufferQueueConsumer(const sp<BufferQueueCore>& core) :
29    mCore(core),
30    mSlots(core->mSlots),
31    mConsumerName() {}
32
33BufferQueueConsumer::~BufferQueueConsumer() {}
34
35status_t BufferQueueConsumer::acquireBuffer(BufferItem* outBuffer,
36        nsecs_t expectedPresent) {
37    ATRACE_CALL();
38    Mutex::Autolock lock(mCore->mMutex);
39
40    // Check that the consumer doesn't currently have the maximum number of
41    // buffers acquired. We allow the max buffer count to be exceeded by one
42    // buffer so that the consumer can successfully set up the newly acquired
43    // buffer before releasing the old one.
44    int numAcquiredBuffers = 0;
45    for (int s = 0; s < BufferQueueDefs::NUM_BUFFER_SLOTS; ++s) {
46        if (mSlots[s].mBufferState == BufferSlot::ACQUIRED) {
47            ++numAcquiredBuffers;
48        }
49    }
50    if (numAcquiredBuffers >= mCore->mMaxAcquiredBufferCount + 1) {
51        BQ_LOGE("acquireBuffer: max acquired buffer count reached: %d (max %d)",
52                numAcquiredBuffers, mCore->mMaxAcquiredBufferCount);
53        return INVALID_OPERATION;
54    }
55
56    // Check if the queue is empty.
57    // In asynchronous mode the list is guaranteed to be one buffer deep,
58    // while in synchronous mode we use the oldest buffer.
59    if (mCore->mQueue.empty()) {
60        return NO_BUFFER_AVAILABLE;
61    }
62
63    BufferQueueCore::Fifo::iterator front(mCore->mQueue.begin());
64
65    // If expectedPresent is specified, we may not want to return a buffer yet.
66    // If it's specified and there's more than one buffer queued, we may want
67    // to drop a buffer.
68    if (expectedPresent != 0) {
69        const int MAX_REASONABLE_NSEC = 1000000000ULL; // 1 second
70
71        // The 'expectedPresent' argument indicates when the buffer is expected
72        // to be presented on-screen. If the buffer's desired present time is
73        // earlier (less) than expectedPresent -- meaning it will be displayed
74        // on time or possibly late if we show it as soon as possible -- we
75        // acquire and return it. If we don't want to display it until after the
76        // expectedPresent time, we return PRESENT_LATER without acquiring it.
77        //
78        // To be safe, we don't defer acquisition if expectedPresent is more
79        // than one second in the future beyond the desired present time
80        // (i.e., we'd be holding the buffer for a long time).
81        //
82        // NOTE: Code assumes monotonic time values from the system clock
83        // are positive.
84
85        // Start by checking to see if we can drop frames. We skip this check if
86        // the timestamps are being auto-generated by Surface. If the app isn't
87        // generating timestamps explicitly, it probably doesn't want frames to
88        // be discarded based on them.
89        while (mCore->mQueue.size() > 1 && !mCore->mQueue[0].mIsAutoTimestamp) {
90            // If entry[1] is timely, drop entry[0] (and repeat). We apply an
91            // additional criterion here: we only drop the earlier buffer if our
92            // desiredPresent falls within +/- 1 second of the expected present.
93            // Otherwise, bogus desiredPresent times (e.g., 0 or a small
94            // relative timestamp), which normally mean "ignore the timestamp
95            // and acquire immediately", would cause us to drop frames.
96            //
97            // We may want to add an additional criterion: don't drop the
98            // earlier buffer if entry[1]'s fence hasn't signaled yet.
99            const BufferItem& bufferItem(mCore->mQueue[1]);
100            nsecs_t desiredPresent = bufferItem.mTimestamp;
101            if (desiredPresent < expectedPresent - MAX_REASONABLE_NSEC ||
102                    desiredPresent > expectedPresent) {
103                // This buffer is set to display in the near future, or
104                // desiredPresent is garbage. Either way we don't want to drop
105                // the previous buffer just to get this on the screen sooner.
106                BQ_LOGV("acquireBuffer: nodrop desire=%lld expect=%lld "
107                        "(%lld) now=%lld", desiredPresent, expectedPresent,
108                        desiredPresent - expectedPresent,
109                        systemTime(CLOCK_MONOTONIC));
110                break;
111            }
112
113            BQ_LOGV("acquireBuffer: drop desire=%lld expect=%lld size=%d",
114                    desiredPresent, expectedPresent, mCore->mQueue.size());
115            if (mCore->stillTracking(front)) {
116                // Front buffer is still in mSlots, so mark the slot as free
117                mSlots[front->mSlot].mBufferState = BufferSlot::FREE;
118            }
119            mCore->mQueue.erase(front);
120            front = mCore->mQueue.begin();
121        }
122
123        // See if the front buffer is due
124        nsecs_t desiredPresent = front->mTimestamp;
125        if (desiredPresent > expectedPresent &&
126                desiredPresent < expectedPresent + MAX_REASONABLE_NSEC) {
127            BQ_LOGV("acquireBuffer: defer desire=%lld expect=%lld "
128                    "(%lld) now=%lld", desiredPresent, expectedPresent,
129                    desiredPresent - expectedPresent,
130                    systemTime(CLOCK_MONOTONIC));
131            return PRESENT_LATER;
132        }
133
134        BQ_LOGV("acquireBuffer: accept desire=%lld expect=%lld "
135                "(%lld) now=%lld", desiredPresent, expectedPresent,
136                desiredPresent - expectedPresent,
137                systemTime(CLOCK_MONOTONIC));
138    }
139
140    int slot = front->mSlot;
141    *outBuffer = *front;
142    ATRACE_BUFFER_INDEX(slot);
143
144    BQ_LOGV("acquireBuffer: acquiring { slot=%d/%llu buffer=%p }",
145            slot, front->mFrameNumber, front->mGraphicBuffer->handle);
146    // If the front buffer is still being tracked, update its slot state
147    if (mCore->stillTracking(front)) {
148        mSlots[slot].mAcquireCalled = true;
149        mSlots[slot].mNeedsCleanupOnRelease = false;
150        mSlots[slot].mBufferState = BufferSlot::ACQUIRED;
151        mSlots[slot].mFence = Fence::NO_FENCE;
152    }
153
154    // If the buffer has previously been acquired by the consumer, set
155    // mGraphicBuffer to NULL to avoid unnecessarily remapping this buffer
156    // on the consumer side
157    if (outBuffer->mAcquireCalled) {
158        outBuffer->mGraphicBuffer = NULL;
159    }
160
161    mCore->mQueue.erase(front);
162    // TODO: Should this call be after we free a slot while dropping buffers?
163    // Simply acquiring the next buffer doesn't enable a producer to dequeue.
164    mCore->mDequeueCondition.broadcast();
165
166    ATRACE_INT(mCore->mConsumerName.string(), mCore->mQueue.size());
167
168    return NO_ERROR;
169}
170
171status_t BufferQueueConsumer::detachBuffer(int slot) {
172    ATRACE_CALL();
173    ATRACE_BUFFER_INDEX(slot);
174    BQ_LOGV("detachBuffer(C): slot %d", slot);
175    Mutex::Autolock lock(mCore->mMutex);
176
177    if (mCore->mIsAbandoned) {
178        BQ_LOGE("detachBuffer(C): BufferQueue has been abandoned");
179        return NO_INIT;
180    }
181
182    if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS) {
183        BQ_LOGE("detachBuffer(C): slot index %d out of range [0, %d)",
184                slot, BufferQueueDefs::NUM_BUFFER_SLOTS);
185        return BAD_VALUE;
186    } else if (mSlots[slot].mBufferState != BufferSlot::ACQUIRED) {
187        BQ_LOGE("detachBuffer(C): slot %d is not owned by the consumer "
188                "(state = %d)", slot, mSlots[slot].mBufferState);
189        return BAD_VALUE;
190    }
191
192    mCore->freeBufferLocked(slot);
193    mCore->mDequeueCondition.broadcast();
194
195    return NO_ERROR;
196}
197
198status_t BufferQueueConsumer::attachBuffer(int* outSlot,
199        const sp<android::GraphicBuffer>& buffer) {
200    ATRACE_CALL();
201
202    if (outSlot == NULL) {
203        BQ_LOGE("attachBuffer(P): outSlot must not be NULL");
204        return BAD_VALUE;
205    } else if (buffer == NULL) {
206        BQ_LOGE("attachBuffer(P): cannot attach NULL buffer");
207        return BAD_VALUE;
208    }
209
210    Mutex::Autolock lock(mCore->mMutex);
211
212    // Make sure we don't have too many acquired buffers and find a free slot
213    // to put the buffer into (the oldest if there are multiple).
214    int numAcquiredBuffers = 0;
215    int found = BufferQueueCore::INVALID_BUFFER_SLOT;
216    for (int s = 0; s < BufferQueueDefs::NUM_BUFFER_SLOTS; ++s) {
217        if (mSlots[s].mBufferState == BufferSlot::ACQUIRED) {
218            ++numAcquiredBuffers;
219        } else if (mSlots[s].mBufferState == BufferSlot::FREE) {
220            if (found == BufferQueueCore::INVALID_BUFFER_SLOT ||
221                    mSlots[s].mFrameNumber < mSlots[found].mFrameNumber) {
222                found = s;
223            }
224        }
225    }
226
227    if (numAcquiredBuffers >= mCore->mMaxAcquiredBufferCount + 1) {
228        BQ_LOGE("attachBuffer(P): max acquired buffer count reached: %d "
229                "(max %d)", numAcquiredBuffers,
230                mCore->mMaxAcquiredBufferCount);
231        return INVALID_OPERATION;
232    }
233    if (found == BufferQueueCore::INVALID_BUFFER_SLOT) {
234        BQ_LOGE("attachBuffer(P): could not find free buffer slot");
235        return NO_MEMORY;
236    }
237
238    *outSlot = found;
239    ATRACE_BUFFER_INDEX(*outSlot);
240    BQ_LOGV("attachBuffer(C): returning slot %d", *outSlot);
241
242    mSlots[*outSlot].mGraphicBuffer = buffer;
243    mSlots[*outSlot].mBufferState = BufferSlot::ACQUIRED;
244    mSlots[*outSlot].mAttachedByConsumer = true;
245    mSlots[*outSlot].mAcquireCalled = true;
246    mSlots[*outSlot].mNeedsCleanupOnRelease = false;
247    mSlots[*outSlot].mFence = Fence::NO_FENCE;
248    mSlots[*outSlot].mFrameNumber = 0;
249
250    return NO_ERROR;
251}
252
253status_t BufferQueueConsumer::releaseBuffer(int slot, uint64_t frameNumber,
254        const sp<Fence>& releaseFence, EGLDisplay eglDisplay,
255        EGLSyncKHR eglFence) {
256    ATRACE_CALL();
257    ATRACE_BUFFER_INDEX(slot);
258
259    if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS ||
260            releaseFence == NULL) {
261        return BAD_VALUE;
262    }
263
264    Mutex::Autolock lock(mCore->mMutex);
265
266    // If the frame number has changed because the buffer has been reallocated,
267    // we can ignore this releaseBuffer for the old buffer
268    if (frameNumber != mSlots[slot].mFrameNumber) {
269        return STALE_BUFFER_SLOT;
270    }
271
272    // Make sure this buffer hasn't been queued while acquired by the consumer
273    BufferQueueCore::Fifo::iterator current(mCore->mQueue.begin());
274    while (current != mCore->mQueue.end()) {
275        if (current->mSlot == slot) {
276            BQ_LOGE("releaseBuffer: buffer slot %d pending release is "
277                    "currently queued", slot);
278            return BAD_VALUE;
279        }
280        ++current;
281    }
282
283    if (mSlots[slot].mBufferState == BufferSlot::ACQUIRED) {
284        mSlots[slot].mEglDisplay = eglDisplay;
285        mSlots[slot].mEglFence = eglFence;
286        mSlots[slot].mFence = releaseFence;
287        mSlots[slot].mBufferState = BufferSlot::FREE;
288    } else if (mSlots[slot].mNeedsCleanupOnRelease) {
289        BQ_LOGV("releaseBuffer: releasing a stale buffer slot %d "
290                "(state = %d)", slot, mSlots[slot].mBufferState);
291        mSlots[slot].mNeedsCleanupOnRelease = false;
292        return STALE_BUFFER_SLOT;
293    } else {
294        BQ_LOGV("releaseBuffer: attempted to release buffer slot %d "
295                "but its state was %d", slot, mSlots[slot].mBufferState);
296        return BAD_VALUE;
297    }
298
299    mCore->mDequeueCondition.broadcast();
300
301    return NO_ERROR;
302}
303
304status_t BufferQueueConsumer::connect(
305        const sp<IConsumerListener>& consumerListener, bool controlledByApp) {
306    ATRACE_CALL();
307
308    if (consumerListener == NULL) {
309        BQ_LOGE("connect(C): consumerListener may not be NULL");
310        return BAD_VALUE;
311    }
312
313    BQ_LOGV("connect(C): controlledByApp=%s",
314            controlledByApp ? "true" : "false");
315
316    Mutex::Autolock lock(mCore->mMutex);
317
318    if (mCore->mIsAbandoned) {
319        BQ_LOGE("connect(C): BufferQueue has been abandoned");
320        return NO_INIT;
321    }
322
323    mCore->mConsumerListener = consumerListener;
324    mCore->mConsumerControlledByApp = controlledByApp;
325
326    return NO_ERROR;
327}
328
329status_t BufferQueueConsumer::disconnect() {
330    ATRACE_CALL();
331
332    BQ_LOGV("disconnect(C)");
333
334    Mutex::Autolock lock(mCore->mMutex);
335
336    if (mCore->mConsumerListener == NULL) {
337        BQ_LOGE("disconnect(C): no consumer is connected");
338        return BAD_VALUE;
339    }
340
341    mCore->mIsAbandoned = true;
342    mCore->mConsumerListener = NULL;
343    mCore->mQueue.clear();
344    mCore->freeAllBuffersLocked();
345    mCore->mDequeueCondition.broadcast();
346    return NO_ERROR;
347}
348
349status_t BufferQueueConsumer::getReleasedBuffers(uint32_t *outSlotMask) {
350    ATRACE_CALL();
351
352    if (outSlotMask == NULL) {
353        BQ_LOGE("getReleasedBuffers: outSlotMask may not be NULL");
354        return BAD_VALUE;
355    }
356
357    Mutex::Autolock lock(mCore->mMutex);
358
359    if (mCore->mIsAbandoned) {
360        BQ_LOGE("getReleasedBuffers: BufferQueue has been abandoned");
361        return NO_INIT;
362    }
363
364    uint32_t mask = 0;
365    for (int s = 0; s < BufferQueueDefs::NUM_BUFFER_SLOTS; ++s) {
366        if (!mSlots[s].mAcquireCalled) {
367            mask |= (1u << s);
368        }
369    }
370
371    // Remove from the mask queued buffers for which acquire has been called,
372    // since the consumer will not receive their buffer addresses and so must
373    // retain their cached information
374    BufferQueueCore::Fifo::iterator current(mCore->mQueue.begin());
375    while (current != mCore->mQueue.end()) {
376        if (current->mAcquireCalled) {
377            mask &= ~(1u << current->mSlot);
378        }
379        ++current;
380    }
381
382    BQ_LOGV("getReleasedBuffers: returning mask %#x", mask);
383    *outSlotMask = mask;
384    return NO_ERROR;
385}
386
387status_t BufferQueueConsumer::setDefaultBufferSize(uint32_t width,
388        uint32_t height) {
389    ATRACE_CALL();
390
391    if (width == 0 || height == 0) {
392        BQ_LOGV("setDefaultBufferSize: dimensions cannot be 0 (width=%u "
393                "height=%u)", width, height);
394        return BAD_VALUE;
395    }
396
397    BQ_LOGV("setDefaultBufferSize: width=%u height=%u", width, height);
398
399    Mutex::Autolock lock(mCore->mMutex);
400    mCore->mDefaultWidth = width;
401    mCore->mDefaultHeight = height;
402    return NO_ERROR;
403}
404
405status_t BufferQueueConsumer::setDefaultMaxBufferCount(int bufferCount) {
406    ATRACE_CALL();
407    Mutex::Autolock lock(mCore->mMutex);
408    return mCore->setDefaultMaxBufferCountLocked(bufferCount);
409}
410
411status_t BufferQueueConsumer::disableAsyncBuffer() {
412    ATRACE_CALL();
413
414    Mutex::Autolock lock(mCore->mMutex);
415
416    if (mCore->mConsumerListener != NULL) {
417        BQ_LOGE("disableAsyncBuffer: consumer already connected");
418        return INVALID_OPERATION;
419    }
420
421    BQ_LOGV("disableAsyncBuffer");
422    mCore->mUseAsyncBuffer = false;
423    return NO_ERROR;
424}
425
426status_t BufferQueueConsumer::setMaxAcquiredBufferCount(
427        int maxAcquiredBuffers) {
428    ATRACE_CALL();
429
430    if (maxAcquiredBuffers < 1 ||
431            maxAcquiredBuffers > BufferQueueCore::MAX_MAX_ACQUIRED_BUFFERS) {
432        BQ_LOGE("setMaxAcquiredBufferCount: invalid count %d",
433                maxAcquiredBuffers);
434        return BAD_VALUE;
435    }
436
437    Mutex::Autolock lock(mCore->mMutex);
438
439    if (mCore->mConnectedApi != BufferQueueCore::NO_CONNECTED_API) {
440        BQ_LOGE("setMaxAcquiredBufferCount: producer is already connected");
441        return INVALID_OPERATION;
442    }
443
444    BQ_LOGV("setMaxAcquiredBufferCount: %d", maxAcquiredBuffers);
445    mCore->mMaxAcquiredBufferCount = maxAcquiredBuffers;
446    return NO_ERROR;
447}
448
449void BufferQueueConsumer::setConsumerName(const String8& name) {
450    ATRACE_CALL();
451    BQ_LOGV("setConsumerName: '%s'", name.string());
452    Mutex::Autolock lock(mCore->mMutex);
453    mCore->mConsumerName = name;
454    mConsumerName = name;
455}
456
457status_t BufferQueueConsumer::setDefaultBufferFormat(uint32_t defaultFormat) {
458    ATRACE_CALL();
459    BQ_LOGV("setDefaultBufferFormat: %u", defaultFormat);
460    Mutex::Autolock lock(mCore->mMutex);
461    mCore->mDefaultBufferFormat = defaultFormat;
462    return NO_ERROR;
463}
464
465status_t BufferQueueConsumer::setConsumerUsageBits(uint32_t usage) {
466    ATRACE_CALL();
467    BQ_LOGV("setConsumerUsageBits: %#x", usage);
468    Mutex::Autolock lock(mCore->mMutex);
469    mCore->mConsumerUsageBits = usage;
470    return NO_ERROR;
471}
472
473status_t BufferQueueConsumer::setTransformHint(uint32_t hint) {
474    ATRACE_CALL();
475    BQ_LOGV("setTransformHint: %#x", hint);
476    Mutex::Autolock lock(mCore->mMutex);
477    mCore->mTransformHint = hint;
478    return NO_ERROR;
479}
480
481void BufferQueueConsumer::dump(String8& result, const char* prefix) const {
482    mCore->dump(result, prefix);
483}
484
485} // namespace android
486