blob: 284ddb2bf44a27bbef2aa4da2849acfac5611843 [file] [log] [blame]
Dan Stoza289ade12014-02-28 11:17:17 -08001/*
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
Mark Salyzyn8f515ce2014-06-09 14:32:04 -070017#include <inttypes.h>
18
Dan Stoza3e96f192014-03-03 10:16:19 -080019#define LOG_TAG "BufferQueueProducer"
20#define ATRACE_TAG ATRACE_TAG_GRAPHICS
21//#define LOG_NDEBUG 0
22
Dan Stoza289ade12014-02-28 11:17:17 -080023#define EGL_EGLEXT_PROTOTYPES
24
25#include <gui/BufferItem.h>
26#include <gui/BufferQueueCore.h>
27#include <gui/BufferQueueProducer.h>
28#include <gui/IConsumerListener.h>
29#include <gui/IGraphicBufferAlloc.h>
Dan Stozaf0eaf252014-03-21 13:05:51 -070030#include <gui/IProducerListener.h>
Dan Stoza289ade12014-02-28 11:17:17 -080031
32#include <utils/Log.h>
33#include <utils/Trace.h>
34
35namespace android {
36
37BufferQueueProducer::BufferQueueProducer(const sp<BufferQueueCore>& core) :
38 mCore(core),
39 mSlots(core->mSlots),
Ruben Brunk1681d952014-06-27 15:51:55 -070040 mConsumerName(),
Eric Penner99a0afb2014-09-30 11:28:30 -070041 mStickyTransform(0),
42 mLastQueueBufferFence(Fence::NO_FENCE) {}
Dan Stoza289ade12014-02-28 11:17:17 -080043
44BufferQueueProducer::~BufferQueueProducer() {}
45
46status_t BufferQueueProducer::requestBuffer(int slot, sp<GraphicBuffer>* buf) {
47 ATRACE_CALL();
48 BQ_LOGV("requestBuffer: slot %d", slot);
49 Mutex::Autolock lock(mCore->mMutex);
50
51 if (mCore->mIsAbandoned) {
52 BQ_LOGE("requestBuffer: BufferQueue has been abandoned");
53 return NO_INIT;
54 }
55
Dan Stoza3e96f192014-03-03 10:16:19 -080056 if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS) {
Dan Stoza289ade12014-02-28 11:17:17 -080057 BQ_LOGE("requestBuffer: slot index %d out of range [0, %d)",
Dan Stoza3e96f192014-03-03 10:16:19 -080058 slot, BufferQueueDefs::NUM_BUFFER_SLOTS);
Dan Stoza289ade12014-02-28 11:17:17 -080059 return BAD_VALUE;
60 } else if (mSlots[slot].mBufferState != BufferSlot::DEQUEUED) {
61 BQ_LOGE("requestBuffer: slot %d is not owned by the producer "
62 "(state = %d)", slot, mSlots[slot].mBufferState);
63 return BAD_VALUE;
64 }
65
66 mSlots[slot].mRequestBufferCalled = true;
67 *buf = mSlots[slot].mGraphicBuffer;
68 return NO_ERROR;
69}
70
71status_t BufferQueueProducer::setBufferCount(int bufferCount) {
72 ATRACE_CALL();
73 BQ_LOGV("setBufferCount: count = %d", bufferCount);
74
75 sp<IConsumerListener> listener;
76 { // Autolock scope
77 Mutex::Autolock lock(mCore->mMutex);
Antoine Labour78014f32014-07-15 21:17:03 -070078 mCore->waitWhileAllocatingLocked();
Dan Stoza289ade12014-02-28 11:17:17 -080079
80 if (mCore->mIsAbandoned) {
81 BQ_LOGE("setBufferCount: BufferQueue has been abandoned");
82 return NO_INIT;
83 }
84
Dan Stoza3e96f192014-03-03 10:16:19 -080085 if (bufferCount > BufferQueueDefs::NUM_BUFFER_SLOTS) {
Dan Stoza289ade12014-02-28 11:17:17 -080086 BQ_LOGE("setBufferCount: bufferCount %d too large (max %d)",
Dan Stoza3e96f192014-03-03 10:16:19 -080087 bufferCount, BufferQueueDefs::NUM_BUFFER_SLOTS);
Dan Stoza289ade12014-02-28 11:17:17 -080088 return BAD_VALUE;
89 }
90
91 // There must be no dequeued buffers when changing the buffer count.
Dan Stoza3e96f192014-03-03 10:16:19 -080092 for (int s = 0; s < BufferQueueDefs::NUM_BUFFER_SLOTS; ++s) {
Dan Stoza289ade12014-02-28 11:17:17 -080093 if (mSlots[s].mBufferState == BufferSlot::DEQUEUED) {
94 BQ_LOGE("setBufferCount: buffer owned by producer");
Dan Stoza9f3053d2014-03-06 15:14:33 -080095 return BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -080096 }
97 }
98
99 if (bufferCount == 0) {
100 mCore->mOverrideMaxBufferCount = 0;
101 mCore->mDequeueCondition.broadcast();
102 return NO_ERROR;
103 }
104
105 const int minBufferSlots = mCore->getMinMaxBufferCountLocked(false);
106 if (bufferCount < minBufferSlots) {
107 BQ_LOGE("setBufferCount: requested buffer count %d is less than "
108 "minimum %d", bufferCount, minBufferSlots);
109 return BAD_VALUE;
110 }
111
112 // Here we are guaranteed that the producer doesn't have any dequeued
113 // buffers and will release all of its buffer references. We don't
114 // clear the queue, however, so that currently queued buffers still
115 // get displayed.
116 mCore->freeAllBuffersLocked();
117 mCore->mOverrideMaxBufferCount = bufferCount;
118 mCore->mDequeueCondition.broadcast();
119 listener = mCore->mConsumerListener;
120 } // Autolock scope
121
122 // Call back without lock held
123 if (listener != NULL) {
124 listener->onBuffersReleased();
125 }
126
127 return NO_ERROR;
128}
129
Dan Stoza9f3053d2014-03-06 15:14:33 -0800130status_t BufferQueueProducer::waitForFreeSlotThenRelock(const char* caller,
131 bool async, int* found, status_t* returnFlags) const {
132 bool tryAgain = true;
133 while (tryAgain) {
134 if (mCore->mIsAbandoned) {
135 BQ_LOGE("%s: BufferQueue has been abandoned", caller);
136 return NO_INIT;
137 }
138
139 const int maxBufferCount = mCore->getMaxBufferCountLocked(async);
140 if (async && mCore->mOverrideMaxBufferCount) {
141 // FIXME: Some drivers are manually setting the buffer count
142 // (which they shouldn't), so we do this extra test here to
143 // handle that case. This is TEMPORARY until we get this fixed.
144 if (mCore->mOverrideMaxBufferCount < maxBufferCount) {
145 BQ_LOGE("%s: async mode is invalid with buffer count override",
146 caller);
147 return BAD_VALUE;
148 }
149 }
150
151 // Free up any buffers that are in slots beyond the max buffer count
152 for (int s = maxBufferCount; s < BufferQueueDefs::NUM_BUFFER_SLOTS; ++s) {
153 assert(mSlots[s].mBufferState == BufferSlot::FREE);
154 if (mSlots[s].mGraphicBuffer != NULL) {
155 mCore->freeBufferLocked(s);
156 *returnFlags |= RELEASE_ALL_BUFFERS;
157 }
158 }
159
160 // Look for a free buffer to give to the client
161 *found = BufferQueueCore::INVALID_BUFFER_SLOT;
162 int dequeuedCount = 0;
163 int acquiredCount = 0;
164 for (int s = 0; s < maxBufferCount; ++s) {
165 switch (mSlots[s].mBufferState) {
166 case BufferSlot::DEQUEUED:
167 ++dequeuedCount;
168 break;
169 case BufferSlot::ACQUIRED:
170 ++acquiredCount;
171 break;
172 case BufferSlot::FREE:
173 // We return the oldest of the free buffers to avoid
174 // stalling the producer if possible, since the consumer
175 // may still have pending reads of in-flight buffers
176 if (*found == BufferQueueCore::INVALID_BUFFER_SLOT ||
177 mSlots[s].mFrameNumber < mSlots[*found].mFrameNumber) {
178 *found = s;
179 }
180 break;
181 default:
182 break;
183 }
184 }
185
186 // Producers are not allowed to dequeue more than one buffer if they
187 // did not set a buffer count
188 if (!mCore->mOverrideMaxBufferCount && dequeuedCount) {
189 BQ_LOGE("%s: can't dequeue multiple buffers without setting the "
190 "buffer count", caller);
191 return INVALID_OPERATION;
192 }
193
194 // See whether a buffer has been queued since the last
195 // setBufferCount so we know whether to perform the min undequeued
196 // buffers check below
197 if (mCore->mBufferHasBeenQueued) {
198 // Make sure the producer is not trying to dequeue more buffers
199 // than allowed
200 const int newUndequeuedCount =
201 maxBufferCount - (dequeuedCount + 1);
202 const int minUndequeuedCount =
203 mCore->getMinUndequeuedBufferCountLocked(async);
204 if (newUndequeuedCount < minUndequeuedCount) {
205 BQ_LOGE("%s: min undequeued buffer count (%d) exceeded "
206 "(dequeued=%d undequeued=%d)",
207 caller, minUndequeuedCount,
208 dequeuedCount, newUndequeuedCount);
209 return INVALID_OPERATION;
210 }
211 }
212
Dan Stozaae3c3682014-04-18 15:43:35 -0700213 // If we disconnect and reconnect quickly, we can be in a state where
214 // our slots are empty but we have many buffers in the queue. This can
215 // cause us to run out of memory if we outrun the consumer. Wait here if
216 // it looks like we have too many buffers queued up.
Mark Salyzyn8f515ce2014-06-09 14:32:04 -0700217 bool tooManyBuffers = mCore->mQueue.size()
218 > static_cast<size_t>(maxBufferCount);
Dan Stozaae3c3682014-04-18 15:43:35 -0700219 if (tooManyBuffers) {
Mark Salyzyn8f515ce2014-06-09 14:32:04 -0700220 BQ_LOGV("%s: queue size is %zu, waiting", caller,
Dan Stozaae3c3682014-04-18 15:43:35 -0700221 mCore->mQueue.size());
222 }
223
224 // If no buffer is found, or if the queue has too many buffers
225 // outstanding, wait for a buffer to be acquired or released, or for the
226 // max buffer count to change.
227 tryAgain = (*found == BufferQueueCore::INVALID_BUFFER_SLOT) ||
228 tooManyBuffers;
Dan Stoza9f3053d2014-03-06 15:14:33 -0800229 if (tryAgain) {
230 // Return an error if we're in non-blocking mode (producer and
231 // consumer are controlled by the application).
232 // However, the consumer is allowed to briefly acquire an extra
233 // buffer (which could cause us to have to wait here), which is
234 // okay, since it is only used to implement an atomic acquire +
235 // release (e.g., in GLConsumer::updateTexImage())
236 if (mCore->mDequeueBufferCannotBlock &&
237 (acquiredCount <= mCore->mMaxAcquiredBufferCount)) {
238 return WOULD_BLOCK;
239 }
240 mCore->mDequeueCondition.wait(mCore->mMutex);
241 }
242 } // while (tryAgain)
243
244 return NO_ERROR;
245}
246
Dan Stoza289ade12014-02-28 11:17:17 -0800247status_t BufferQueueProducer::dequeueBuffer(int *outSlot,
248 sp<android::Fence> *outFence, bool async,
249 uint32_t width, uint32_t height, uint32_t format, uint32_t usage) {
250 ATRACE_CALL();
251 { // Autolock scope
252 Mutex::Autolock lock(mCore->mMutex);
253 mConsumerName = mCore->mConsumerName;
254 } // Autolock scope
255
256 BQ_LOGV("dequeueBuffer: async=%s w=%u h=%u format=%#x, usage=%#x",
257 async ? "true" : "false", width, height, format, usage);
258
259 if ((width && !height) || (!width && height)) {
260 BQ_LOGE("dequeueBuffer: invalid size: w=%u h=%u", width, height);
261 return BAD_VALUE;
262 }
263
264 status_t returnFlags = NO_ERROR;
265 EGLDisplay eglDisplay = EGL_NO_DISPLAY;
266 EGLSyncKHR eglFence = EGL_NO_SYNC_KHR;
Dan Stoza9f3053d2014-03-06 15:14:33 -0800267 bool attachedByConsumer = false;
Dan Stoza289ade12014-02-28 11:17:17 -0800268
269 { // Autolock scope
270 Mutex::Autolock lock(mCore->mMutex);
Antoine Labour78014f32014-07-15 21:17:03 -0700271 mCore->waitWhileAllocatingLocked();
Dan Stoza289ade12014-02-28 11:17:17 -0800272
273 if (format == 0) {
274 format = mCore->mDefaultBufferFormat;
275 }
276
277 // Enable the usage bits the consumer requested
278 usage |= mCore->mConsumerUsageBits;
279
Dan Stoza9f3053d2014-03-06 15:14:33 -0800280 int found;
281 status_t status = waitForFreeSlotThenRelock("dequeueBuffer", async,
282 &found, &returnFlags);
283 if (status != NO_ERROR) {
284 return status;
285 }
Dan Stoza289ade12014-02-28 11:17:17 -0800286
287 // This should not happen
288 if (found == BufferQueueCore::INVALID_BUFFER_SLOT) {
289 BQ_LOGE("dequeueBuffer: no available buffer slots");
290 return -EBUSY;
291 }
292
293 *outSlot = found;
294 ATRACE_BUFFER_INDEX(found);
295
Dan Stoza9f3053d2014-03-06 15:14:33 -0800296 attachedByConsumer = mSlots[found].mAttachedByConsumer;
297
Dan Stoza289ade12014-02-28 11:17:17 -0800298 const bool useDefaultSize = !width && !height;
299 if (useDefaultSize) {
300 width = mCore->mDefaultWidth;
301 height = mCore->mDefaultHeight;
302 }
303
304 mSlots[found].mBufferState = BufferSlot::DEQUEUED;
305
306 const sp<GraphicBuffer>& buffer(mSlots[found].mGraphicBuffer);
307 if ((buffer == NULL) ||
308 (static_cast<uint32_t>(buffer->width) != width) ||
309 (static_cast<uint32_t>(buffer->height) != height) ||
310 (static_cast<uint32_t>(buffer->format) != format) ||
311 ((static_cast<uint32_t>(buffer->usage) & usage) != usage))
312 {
313 mSlots[found].mAcquireCalled = false;
314 mSlots[found].mGraphicBuffer = NULL;
315 mSlots[found].mRequestBufferCalled = false;
316 mSlots[found].mEglDisplay = EGL_NO_DISPLAY;
317 mSlots[found].mEglFence = EGL_NO_SYNC_KHR;
318 mSlots[found].mFence = Fence::NO_FENCE;
319
320 returnFlags |= BUFFER_NEEDS_REALLOCATION;
321 }
322
323 if (CC_UNLIKELY(mSlots[found].mFence == NULL)) {
324 BQ_LOGE("dequeueBuffer: about to return a NULL fence - "
325 "slot=%d w=%d h=%d format=%u",
326 found, buffer->width, buffer->height, buffer->format);
327 }
328
329 eglDisplay = mSlots[found].mEglDisplay;
330 eglFence = mSlots[found].mEglFence;
331 *outFence = mSlots[found].mFence;
332 mSlots[found].mEglFence = EGL_NO_SYNC_KHR;
333 mSlots[found].mFence = Fence::NO_FENCE;
334 } // Autolock scope
335
336 if (returnFlags & BUFFER_NEEDS_REALLOCATION) {
337 status_t error;
Dan Stoza29a3e902014-06-20 13:13:57 -0700338 BQ_LOGV("dequeueBuffer: allocating a new buffer for slot %d", *outSlot);
Dan Stoza289ade12014-02-28 11:17:17 -0800339 sp<GraphicBuffer> graphicBuffer(mCore->mAllocator->createGraphicBuffer(
340 width, height, format, usage, &error));
341 if (graphicBuffer == NULL) {
342 BQ_LOGE("dequeueBuffer: createGraphicBuffer failed");
343 return error;
344 }
345
346 { // Autolock scope
347 Mutex::Autolock lock(mCore->mMutex);
348
349 if (mCore->mIsAbandoned) {
350 BQ_LOGE("dequeueBuffer: BufferQueue has been abandoned");
351 return NO_INIT;
352 }
353
Dan Stoza9f3053d2014-03-06 15:14:33 -0800354 mSlots[*outSlot].mFrameNumber = UINT32_MAX;
Dan Stoza289ade12014-02-28 11:17:17 -0800355 mSlots[*outSlot].mGraphicBuffer = graphicBuffer;
356 } // Autolock scope
357 }
358
Dan Stoza9f3053d2014-03-06 15:14:33 -0800359 if (attachedByConsumer) {
360 returnFlags |= BUFFER_NEEDS_REALLOCATION;
361 }
362
Dan Stoza289ade12014-02-28 11:17:17 -0800363 if (eglFence != EGL_NO_SYNC_KHR) {
364 EGLint result = eglClientWaitSyncKHR(eglDisplay, eglFence, 0,
365 1000000000);
366 // If something goes wrong, log the error, but return the buffer without
367 // synchronizing access to it. It's too late at this point to abort the
368 // dequeue operation.
369 if (result == EGL_FALSE) {
370 BQ_LOGE("dequeueBuffer: error %#x waiting for fence",
371 eglGetError());
372 } else if (result == EGL_TIMEOUT_EXPIRED_KHR) {
373 BQ_LOGE("dequeueBuffer: timeout waiting for fence");
374 }
375 eglDestroySyncKHR(eglDisplay, eglFence);
376 }
377
Mark Salyzyn8f515ce2014-06-09 14:32:04 -0700378 BQ_LOGV("dequeueBuffer: returning slot=%d/%" PRIu64 " buf=%p flags=%#x",
379 *outSlot,
Dan Stoza289ade12014-02-28 11:17:17 -0800380 mSlots[*outSlot].mFrameNumber,
381 mSlots[*outSlot].mGraphicBuffer->handle, returnFlags);
382
383 return returnFlags;
384}
385
Dan Stoza9f3053d2014-03-06 15:14:33 -0800386status_t BufferQueueProducer::detachBuffer(int slot) {
387 ATRACE_CALL();
388 ATRACE_BUFFER_INDEX(slot);
389 BQ_LOGV("detachBuffer(P): slot %d", slot);
390 Mutex::Autolock lock(mCore->mMutex);
391
392 if (mCore->mIsAbandoned) {
393 BQ_LOGE("detachBuffer(P): BufferQueue has been abandoned");
394 return NO_INIT;
395 }
396
397 if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS) {
398 BQ_LOGE("detachBuffer(P): slot index %d out of range [0, %d)",
399 slot, BufferQueueDefs::NUM_BUFFER_SLOTS);
400 return BAD_VALUE;
401 } else if (mSlots[slot].mBufferState != BufferSlot::DEQUEUED) {
402 BQ_LOGE("detachBuffer(P): slot %d is not owned by the producer "
403 "(state = %d)", slot, mSlots[slot].mBufferState);
404 return BAD_VALUE;
405 } else if (!mSlots[slot].mRequestBufferCalled) {
406 BQ_LOGE("detachBuffer(P): buffer in slot %d has not been requested",
407 slot);
408 return BAD_VALUE;
409 }
410
411 mCore->freeBufferLocked(slot);
412 mCore->mDequeueCondition.broadcast();
413
414 return NO_ERROR;
415}
416
Dan Stozad9822a32014-03-28 15:25:31 -0700417status_t BufferQueueProducer::detachNextBuffer(sp<GraphicBuffer>* outBuffer,
418 sp<Fence>* outFence) {
419 ATRACE_CALL();
420
421 if (outBuffer == NULL) {
422 BQ_LOGE("detachNextBuffer: outBuffer must not be NULL");
423 return BAD_VALUE;
424 } else if (outFence == NULL) {
425 BQ_LOGE("detachNextBuffer: outFence must not be NULL");
426 return BAD_VALUE;
427 }
428
429 Mutex::Autolock lock(mCore->mMutex);
Antoine Labour78014f32014-07-15 21:17:03 -0700430 mCore->waitWhileAllocatingLocked();
Dan Stozad9822a32014-03-28 15:25:31 -0700431
432 if (mCore->mIsAbandoned) {
433 BQ_LOGE("detachNextBuffer: BufferQueue has been abandoned");
434 return NO_INIT;
435 }
436
437 // Find the oldest valid slot
438 int found = BufferQueueCore::INVALID_BUFFER_SLOT;
439 for (int s = 0; s < BufferQueueDefs::NUM_BUFFER_SLOTS; ++s) {
440 if (mSlots[s].mBufferState == BufferSlot::FREE &&
441 mSlots[s].mGraphicBuffer != NULL) {
442 if (found == BufferQueueCore::INVALID_BUFFER_SLOT ||
443 mSlots[s].mFrameNumber < mSlots[found].mFrameNumber) {
444 found = s;
445 }
446 }
447 }
448
449 if (found == BufferQueueCore::INVALID_BUFFER_SLOT) {
450 return NO_MEMORY;
451 }
452
453 BQ_LOGV("detachNextBuffer detached slot %d", found);
454
455 *outBuffer = mSlots[found].mGraphicBuffer;
456 *outFence = mSlots[found].mFence;
457 mCore->freeBufferLocked(found);
458
459 return NO_ERROR;
460}
461
Dan Stoza9f3053d2014-03-06 15:14:33 -0800462status_t BufferQueueProducer::attachBuffer(int* outSlot,
463 const sp<android::GraphicBuffer>& buffer) {
464 ATRACE_CALL();
465
466 if (outSlot == NULL) {
467 BQ_LOGE("attachBuffer(P): outSlot must not be NULL");
468 return BAD_VALUE;
469 } else if (buffer == NULL) {
470 BQ_LOGE("attachBuffer(P): cannot attach NULL buffer");
471 return BAD_VALUE;
472 }
473
474 Mutex::Autolock lock(mCore->mMutex);
Antoine Labour78014f32014-07-15 21:17:03 -0700475 mCore->waitWhileAllocatingLocked();
Dan Stoza9f3053d2014-03-06 15:14:33 -0800476
477 status_t returnFlags = NO_ERROR;
478 int found;
479 // TODO: Should we provide an async flag to attachBuffer? It seems
480 // unlikely that buffers which we are attaching to a BufferQueue will
481 // be asynchronous (droppable), but it may not be impossible.
482 status_t status = waitForFreeSlotThenRelock("attachBuffer(P)", false,
483 &found, &returnFlags);
484 if (status != NO_ERROR) {
485 return status;
486 }
487
488 // This should not happen
489 if (found == BufferQueueCore::INVALID_BUFFER_SLOT) {
490 BQ_LOGE("attachBuffer(P): no available buffer slots");
491 return -EBUSY;
492 }
493
494 *outSlot = found;
495 ATRACE_BUFFER_INDEX(*outSlot);
496 BQ_LOGV("attachBuffer(P): returning slot %d flags=%#x",
497 *outSlot, returnFlags);
498
499 mSlots[*outSlot].mGraphicBuffer = buffer;
500 mSlots[*outSlot].mBufferState = BufferSlot::DEQUEUED;
501 mSlots[*outSlot].mEglFence = EGL_NO_SYNC_KHR;
502 mSlots[*outSlot].mFence = Fence::NO_FENCE;
Dan Stoza2443c792014-03-24 15:03:46 -0700503 mSlots[*outSlot].mRequestBufferCalled = true;
Dan Stoza9f3053d2014-03-06 15:14:33 -0800504
505 return returnFlags;
506}
507
Dan Stoza289ade12014-02-28 11:17:17 -0800508status_t BufferQueueProducer::queueBuffer(int slot,
509 const QueueBufferInput &input, QueueBufferOutput *output) {
510 ATRACE_CALL();
511 ATRACE_BUFFER_INDEX(slot);
512
513 int64_t timestamp;
514 bool isAutoTimestamp;
515 Rect crop;
516 int scalingMode;
517 uint32_t transform;
Ruben Brunk1681d952014-06-27 15:51:55 -0700518 uint32_t stickyTransform;
Dan Stoza289ade12014-02-28 11:17:17 -0800519 bool async;
520 sp<Fence> fence;
521 input.deflate(&timestamp, &isAutoTimestamp, &crop, &scalingMode, &transform,
Ruben Brunk1681d952014-06-27 15:51:55 -0700522 &async, &fence, &stickyTransform);
Dan Stoza289ade12014-02-28 11:17:17 -0800523
524 if (fence == NULL) {
525 BQ_LOGE("queueBuffer: fence is NULL");
Jesse Hall5b0cbcf2014-10-18 21:47:04 -0700526 // Temporary workaround for b/17946343: soldier-on instead of returning an error. This
527 // prevents the client from dying, at the risk of visible corruption due to hwcomposer
528 // reading the buffer before the producer is done rendering it. Unless the buffer is the
529 // last frame of an animation, the corruption will be transient.
530 fence = Fence::NO_FENCE;
531 // return BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -0800532 }
533
534 switch (scalingMode) {
535 case NATIVE_WINDOW_SCALING_MODE_FREEZE:
536 case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW:
537 case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP:
538 case NATIVE_WINDOW_SCALING_MODE_NO_SCALE_CROP:
539 break;
540 default:
541 BQ_LOGE("queueBuffer: unknown scaling mode %d", scalingMode);
Dan Stoza9f3053d2014-03-06 15:14:33 -0800542 return BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -0800543 }
544
545 sp<IConsumerListener> listener;
546 { // Autolock scope
547 Mutex::Autolock lock(mCore->mMutex);
548
549 if (mCore->mIsAbandoned) {
550 BQ_LOGE("queueBuffer: BufferQueue has been abandoned");
551 return NO_INIT;
552 }
553
554 const int maxBufferCount = mCore->getMaxBufferCountLocked(async);
555 if (async && mCore->mOverrideMaxBufferCount) {
556 // FIXME: Some drivers are manually setting the buffer count
557 // (which they shouldn't), so we do this extra test here to
558 // handle that case. This is TEMPORARY until we get this fixed.
559 if (mCore->mOverrideMaxBufferCount < maxBufferCount) {
560 BQ_LOGE("queueBuffer: async mode is invalid with "
561 "buffer count override");
562 return BAD_VALUE;
563 }
564 }
565
566 if (slot < 0 || slot >= maxBufferCount) {
567 BQ_LOGE("queueBuffer: slot index %d out of range [0, %d)",
568 slot, maxBufferCount);
Dan Stoza9f3053d2014-03-06 15:14:33 -0800569 return BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -0800570 } else if (mSlots[slot].mBufferState != BufferSlot::DEQUEUED) {
571 BQ_LOGE("queueBuffer: slot %d is not owned by the producer "
572 "(state = %d)", slot, mSlots[slot].mBufferState);
Dan Stoza9f3053d2014-03-06 15:14:33 -0800573 return BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -0800574 } else if (!mSlots[slot].mRequestBufferCalled) {
575 BQ_LOGE("queueBuffer: slot %d was queued without requesting "
576 "a buffer", slot);
Dan Stoza9f3053d2014-03-06 15:14:33 -0800577 return BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -0800578 }
579
Mark Salyzyn8f515ce2014-06-09 14:32:04 -0700580 BQ_LOGV("queueBuffer: slot=%d/%" PRIu64 " time=%" PRIu64
581 " crop=[%d,%d,%d,%d] transform=%#x scale=%s",
Dan Stoza289ade12014-02-28 11:17:17 -0800582 slot, mCore->mFrameCounter + 1, timestamp,
583 crop.left, crop.top, crop.right, crop.bottom,
584 transform, BufferItem::scalingModeName(scalingMode));
585
586 const sp<GraphicBuffer>& graphicBuffer(mSlots[slot].mGraphicBuffer);
587 Rect bufferRect(graphicBuffer->getWidth(), graphicBuffer->getHeight());
588 Rect croppedRect;
589 crop.intersect(bufferRect, &croppedRect);
590 if (croppedRect != crop) {
591 BQ_LOGE("queueBuffer: crop rect is not contained within the "
592 "buffer in slot %d", slot);
Dan Stoza9f3053d2014-03-06 15:14:33 -0800593 return BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -0800594 }
595
596 mSlots[slot].mFence = fence;
597 mSlots[slot].mBufferState = BufferSlot::QUEUED;
598 ++mCore->mFrameCounter;
599 mSlots[slot].mFrameNumber = mCore->mFrameCounter;
600
601 BufferItem item;
602 item.mAcquireCalled = mSlots[slot].mAcquireCalled;
603 item.mGraphicBuffer = mSlots[slot].mGraphicBuffer;
604 item.mCrop = crop;
605 item.mTransform = transform & ~NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY;
606 item.mTransformToDisplayInverse =
607 bool(transform & NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY);
608 item.mScalingMode = scalingMode;
609 item.mTimestamp = timestamp;
610 item.mIsAutoTimestamp = isAutoTimestamp;
611 item.mFrameNumber = mCore->mFrameCounter;
612 item.mSlot = slot;
613 item.mFence = fence;
614 item.mIsDroppable = mCore->mDequeueBufferCannotBlock || async;
615
Ruben Brunk1681d952014-06-27 15:51:55 -0700616 mStickyTransform = stickyTransform;
617
Dan Stoza289ade12014-02-28 11:17:17 -0800618 if (mCore->mQueue.empty()) {
619 // When the queue is empty, we can ignore mDequeueBufferCannotBlock
620 // and simply queue this buffer
621 mCore->mQueue.push_back(item);
622 listener = mCore->mConsumerListener;
623 } else {
624 // When the queue is not empty, we need to look at the front buffer
625 // state to see if we need to replace it
626 BufferQueueCore::Fifo::iterator front(mCore->mQueue.begin());
627 if (front->mIsDroppable) {
628 // If the front queued buffer is still being tracked, we first
629 // mark it as freed
630 if (mCore->stillTracking(front)) {
631 mSlots[front->mSlot].mBufferState = BufferSlot::FREE;
632 // Reset the frame number of the freed buffer so that it is
633 // the first in line to be dequeued again
634 mSlots[front->mSlot].mFrameNumber = 0;
635 }
636 // Overwrite the droppable buffer with the incoming one
637 *front = item;
638 } else {
639 mCore->mQueue.push_back(item);
640 listener = mCore->mConsumerListener;
641 }
642 }
643
644 mCore->mBufferHasBeenQueued = true;
645 mCore->mDequeueCondition.broadcast();
646
647 output->inflate(mCore->mDefaultWidth, mCore->mDefaultHeight,
648 mCore->mTransformHint, mCore->mQueue.size());
649
650 ATRACE_INT(mCore->mConsumerName.string(), mCore->mQueue.size());
651 } // Autolock scope
652
Eric Penner99a0afb2014-09-30 11:28:30 -0700653 // Wait without lock held
654 if (mCore->mConnectedApi == NATIVE_WINDOW_API_EGL) {
655 // Waiting here allows for two full buffers to be queued but not a
656 // third. In the event that frames take varying time, this makes a
657 // small trade-off in favor of latency rather than throughput.
658 mLastQueueBufferFence->waitForever("Throttling EGL Production");
659 mLastQueueBufferFence = fence;
660 }
661
Dan Stoza289ade12014-02-28 11:17:17 -0800662 // Call back without lock held
663 if (listener != NULL) {
664 listener->onFrameAvailable();
665 }
666
667 return NO_ERROR;
668}
669
670void BufferQueueProducer::cancelBuffer(int slot, const sp<Fence>& fence) {
671 ATRACE_CALL();
672 BQ_LOGV("cancelBuffer: slot %d", slot);
673 Mutex::Autolock lock(mCore->mMutex);
674
675 if (mCore->mIsAbandoned) {
676 BQ_LOGE("cancelBuffer: BufferQueue has been abandoned");
677 return;
678 }
679
Dan Stoza3e96f192014-03-03 10:16:19 -0800680 if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS) {
Dan Stoza289ade12014-02-28 11:17:17 -0800681 BQ_LOGE("cancelBuffer: slot index %d out of range [0, %d)",
Dan Stoza3e96f192014-03-03 10:16:19 -0800682 slot, BufferQueueDefs::NUM_BUFFER_SLOTS);
Dan Stoza289ade12014-02-28 11:17:17 -0800683 return;
684 } else if (mSlots[slot].mBufferState != BufferSlot::DEQUEUED) {
685 BQ_LOGE("cancelBuffer: slot %d is not owned by the producer "
686 "(state = %d)", slot, mSlots[slot].mBufferState);
687 return;
688 } else if (fence == NULL) {
689 BQ_LOGE("cancelBuffer: fence is NULL");
690 return;
691 }
692
693 mSlots[slot].mBufferState = BufferSlot::FREE;
694 mSlots[slot].mFrameNumber = 0;
695 mSlots[slot].mFence = fence;
696 mCore->mDequeueCondition.broadcast();
697}
698
699int BufferQueueProducer::query(int what, int *outValue) {
700 ATRACE_CALL();
701 Mutex::Autolock lock(mCore->mMutex);
702
703 if (outValue == NULL) {
704 BQ_LOGE("query: outValue was NULL");
705 return BAD_VALUE;
706 }
707
708 if (mCore->mIsAbandoned) {
709 BQ_LOGE("query: BufferQueue has been abandoned");
710 return NO_INIT;
711 }
712
713 int value;
714 switch (what) {
715 case NATIVE_WINDOW_WIDTH:
716 value = mCore->mDefaultWidth;
717 break;
718 case NATIVE_WINDOW_HEIGHT:
719 value = mCore->mDefaultHeight;
720 break;
721 case NATIVE_WINDOW_FORMAT:
722 value = mCore->mDefaultBufferFormat;
723 break;
724 case NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS:
725 value = mCore->getMinUndequeuedBufferCountLocked(false);
726 break;
Ruben Brunk1681d952014-06-27 15:51:55 -0700727 case NATIVE_WINDOW_STICKY_TRANSFORM:
728 value = static_cast<int>(mStickyTransform);
729 break;
Dan Stoza289ade12014-02-28 11:17:17 -0800730 case NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND:
731 value = (mCore->mQueue.size() > 1);
732 break;
733 case NATIVE_WINDOW_CONSUMER_USAGE_BITS:
734 value = mCore->mConsumerUsageBits;
735 break;
736 default:
737 return BAD_VALUE;
738 }
739
740 BQ_LOGV("query: %d? %d", what, value);
741 *outValue = value;
742 return NO_ERROR;
743}
744
Dan Stozaf0eaf252014-03-21 13:05:51 -0700745status_t BufferQueueProducer::connect(const sp<IProducerListener>& listener,
Dan Stoza289ade12014-02-28 11:17:17 -0800746 int api, bool producerControlledByApp, QueueBufferOutput *output) {
747 ATRACE_CALL();
748 Mutex::Autolock lock(mCore->mMutex);
749 mConsumerName = mCore->mConsumerName;
750 BQ_LOGV("connect(P): api=%d producerControlledByApp=%s", api,
751 producerControlledByApp ? "true" : "false");
752
Dan Stozaae3c3682014-04-18 15:43:35 -0700753 if (mCore->mIsAbandoned) {
754 BQ_LOGE("connect(P): BufferQueue has been abandoned");
755 return NO_INIT;
756 }
Dan Stoza289ade12014-02-28 11:17:17 -0800757
Dan Stozaae3c3682014-04-18 15:43:35 -0700758 if (mCore->mConsumerListener == NULL) {
759 BQ_LOGE("connect(P): BufferQueue has no consumer");
760 return NO_INIT;
761 }
Dan Stoza289ade12014-02-28 11:17:17 -0800762
Dan Stozaae3c3682014-04-18 15:43:35 -0700763 if (output == NULL) {
764 BQ_LOGE("connect(P): output was NULL");
765 return BAD_VALUE;
766 }
Dan Stoza289ade12014-02-28 11:17:17 -0800767
Dan Stozaae3c3682014-04-18 15:43:35 -0700768 if (mCore->mConnectedApi != BufferQueueCore::NO_CONNECTED_API) {
769 BQ_LOGE("connect(P): already connected (cur=%d req=%d)",
770 mCore->mConnectedApi, api);
771 return BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -0800772 }
773
774 int status = NO_ERROR;
775 switch (api) {
776 case NATIVE_WINDOW_API_EGL:
777 case NATIVE_WINDOW_API_CPU:
778 case NATIVE_WINDOW_API_MEDIA:
779 case NATIVE_WINDOW_API_CAMERA:
780 mCore->mConnectedApi = api;
781 output->inflate(mCore->mDefaultWidth, mCore->mDefaultHeight,
782 mCore->mTransformHint, mCore->mQueue.size());
783
784 // Set up a death notification so that we can disconnect
785 // automatically if the remote producer dies
Dan Stozaf0eaf252014-03-21 13:05:51 -0700786 if (listener != NULL &&
787 listener->asBinder()->remoteBinder() != NULL) {
788 status = listener->asBinder()->linkToDeath(
Dan Stoza289ade12014-02-28 11:17:17 -0800789 static_cast<IBinder::DeathRecipient*>(this));
Dan Stozaf0eaf252014-03-21 13:05:51 -0700790 if (status != NO_ERROR) {
Dan Stoza289ade12014-02-28 11:17:17 -0800791 BQ_LOGE("connect(P): linkToDeath failed: %s (%d)",
792 strerror(-status), status);
793 }
794 }
Dan Stozaf0eaf252014-03-21 13:05:51 -0700795 mCore->mConnectedProducerListener = listener;
Dan Stoza289ade12014-02-28 11:17:17 -0800796 break;
797 default:
798 BQ_LOGE("connect(P): unknown API %d", api);
799 status = BAD_VALUE;
800 break;
801 }
802
803 mCore->mBufferHasBeenQueued = false;
804 mCore->mDequeueBufferCannotBlock =
805 mCore->mConsumerControlledByApp && producerControlledByApp;
806
807 return status;
808}
809
810status_t BufferQueueProducer::disconnect(int api) {
811 ATRACE_CALL();
812 BQ_LOGV("disconnect(P): api %d", api);
813
814 int status = NO_ERROR;
815 sp<IConsumerListener> listener;
816 { // Autolock scope
817 Mutex::Autolock lock(mCore->mMutex);
Antoine Labour78014f32014-07-15 21:17:03 -0700818 mCore->waitWhileAllocatingLocked();
Dan Stoza289ade12014-02-28 11:17:17 -0800819
820 if (mCore->mIsAbandoned) {
821 // It's not really an error to disconnect after the surface has
822 // been abandoned; it should just be a no-op.
823 return NO_ERROR;
824 }
825
826 switch (api) {
827 case NATIVE_WINDOW_API_EGL:
828 case NATIVE_WINDOW_API_CPU:
829 case NATIVE_WINDOW_API_MEDIA:
830 case NATIVE_WINDOW_API_CAMERA:
831 if (mCore->mConnectedApi == api) {
832 mCore->freeAllBuffersLocked();
833
834 // Remove our death notification callback if we have one
Dan Stozaf0eaf252014-03-21 13:05:51 -0700835 if (mCore->mConnectedProducerListener != NULL) {
836 sp<IBinder> token =
837 mCore->mConnectedProducerListener->asBinder();
Dan Stoza289ade12014-02-28 11:17:17 -0800838 // This can fail if we're here because of the death
839 // notification, but we just ignore it
840 token->unlinkToDeath(
841 static_cast<IBinder::DeathRecipient*>(this));
842 }
Dan Stozaf0eaf252014-03-21 13:05:51 -0700843 mCore->mConnectedProducerListener = NULL;
Dan Stoza289ade12014-02-28 11:17:17 -0800844 mCore->mConnectedApi = BufferQueueCore::NO_CONNECTED_API;
Jesse Hall399184a2014-03-03 15:42:54 -0800845 mCore->mSidebandStream.clear();
Dan Stoza289ade12014-02-28 11:17:17 -0800846 mCore->mDequeueCondition.broadcast();
847 listener = mCore->mConsumerListener;
Michael Lentine45e2fc22014-08-08 10:30:44 -0700848 } else {
849 BQ_LOGE("disconnect(P): connected to another API "
Dan Stoza289ade12014-02-28 11:17:17 -0800850 "(cur=%d req=%d)", mCore->mConnectedApi, api);
Dan Stoza9f3053d2014-03-06 15:14:33 -0800851 status = BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -0800852 }
853 break;
854 default:
855 BQ_LOGE("disconnect(P): unknown API %d", api);
Dan Stoza9f3053d2014-03-06 15:14:33 -0800856 status = BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -0800857 break;
858 }
859 } // Autolock scope
860
861 // Call back without lock held
862 if (listener != NULL) {
863 listener->onBuffersReleased();
864 }
865
866 return status;
867}
868
Jesse Hall399184a2014-03-03 15:42:54 -0800869status_t BufferQueueProducer::setSidebandStream(const sp<NativeHandle>& stream) {
Wonsik Kimafe30812014-03-31 23:16:08 +0900870 sp<IConsumerListener> listener;
871 { // Autolock scope
872 Mutex::Autolock _l(mCore->mMutex);
873 mCore->mSidebandStream = stream;
874 listener = mCore->mConsumerListener;
875 } // Autolock scope
876
877 if (listener != NULL) {
878 listener->onSidebandStreamChanged();
879 }
Jesse Hall399184a2014-03-03 15:42:54 -0800880 return NO_ERROR;
881}
882
Dan Stoza29a3e902014-06-20 13:13:57 -0700883void BufferQueueProducer::allocateBuffers(bool async, uint32_t width,
884 uint32_t height, uint32_t format, uint32_t usage) {
Antoine Labour78014f32014-07-15 21:17:03 -0700885 ATRACE_CALL();
886 while (true) {
887 Vector<int> freeSlots;
888 size_t newBufferCount = 0;
889 uint32_t allocWidth = 0;
890 uint32_t allocHeight = 0;
891 uint32_t allocFormat = 0;
892 uint32_t allocUsage = 0;
893 { // Autolock scope
894 Mutex::Autolock lock(mCore->mMutex);
895 mCore->waitWhileAllocatingLocked();
Dan Stoza29a3e902014-06-20 13:13:57 -0700896
Antoine Labour78014f32014-07-15 21:17:03 -0700897 int currentBufferCount = 0;
898 for (int slot = 0; slot < BufferQueueDefs::NUM_BUFFER_SLOTS; ++slot) {
899 if (mSlots[slot].mGraphicBuffer != NULL) {
900 ++currentBufferCount;
901 } else {
902 if (mSlots[slot].mBufferState != BufferSlot::FREE) {
903 BQ_LOGE("allocateBuffers: slot %d without buffer is not FREE",
904 slot);
905 continue;
906 }
Dan Stoza29a3e902014-06-20 13:13:57 -0700907
Antoine Labour11f14872014-07-25 18:14:42 -0700908 freeSlots.push_back(slot);
Antoine Labour78014f32014-07-15 21:17:03 -0700909 }
910 }
911
912 int maxBufferCount = mCore->getMaxBufferCountLocked(async);
913 BQ_LOGV("allocateBuffers: allocating from %d buffers up to %d buffers",
914 currentBufferCount, maxBufferCount);
915 if (maxBufferCount <= currentBufferCount)
916 return;
917 newBufferCount = maxBufferCount - currentBufferCount;
918 if (freeSlots.size() < newBufferCount) {
919 BQ_LOGE("allocateBuffers: ran out of free slots");
920 return;
921 }
922 allocWidth = width > 0 ? width : mCore->mDefaultWidth;
923 allocHeight = height > 0 ? height : mCore->mDefaultHeight;
924 allocFormat = format != 0 ? format : mCore->mDefaultBufferFormat;
925 allocUsage = usage | mCore->mConsumerUsageBits;
926
927 mCore->mIsAllocating = true;
928 } // Autolock scope
929
930 Vector<sp<GraphicBuffer> > buffers;
931 for (size_t i = 0; i < newBufferCount; ++i) {
932 status_t result = NO_ERROR;
933 sp<GraphicBuffer> graphicBuffer(mCore->mAllocator->createGraphicBuffer(
934 allocWidth, allocHeight, allocFormat, allocUsage, &result));
935 if (result != NO_ERROR) {
936 BQ_LOGE("allocateBuffers: failed to allocate buffer (%u x %u, format"
937 " %u, usage %u)", width, height, format, usage);
938 Mutex::Autolock lock(mCore->mMutex);
939 mCore->mIsAllocating = false;
940 mCore->mIsAllocatingCondition.broadcast();
941 return;
942 }
943 buffers.push_back(graphicBuffer);
944 }
945
946 { // Autolock scope
947 Mutex::Autolock lock(mCore->mMutex);
948 uint32_t checkWidth = width > 0 ? width : mCore->mDefaultWidth;
949 uint32_t checkHeight = height > 0 ? height : mCore->mDefaultHeight;
950 uint32_t checkFormat = format != 0 ? format : mCore->mDefaultBufferFormat;
951 uint32_t checkUsage = usage | mCore->mConsumerUsageBits;
952 if (checkWidth != allocWidth || checkHeight != allocHeight ||
953 checkFormat != allocFormat || checkUsage != allocUsage) {
954 // Something changed while we released the lock. Retry.
955 BQ_LOGV("allocateBuffers: size/format/usage changed while allocating. Retrying.");
956 mCore->mIsAllocating = false;
957 mCore->mIsAllocatingCondition.broadcast();
Dan Stoza29a3e902014-06-20 13:13:57 -0700958 continue;
959 }
960
Antoine Labour78014f32014-07-15 21:17:03 -0700961 for (size_t i = 0; i < newBufferCount; ++i) {
962 int slot = freeSlots[i];
963 if (mSlots[slot].mBufferState != BufferSlot::FREE) {
964 // A consumer allocated the FREE slot with attachBuffer. Discard the buffer we
965 // allocated.
966 BQ_LOGV("allocateBuffers: slot %d was acquired while allocating. "
967 "Dropping allocated buffer.", slot);
968 continue;
969 }
970 mCore->freeBufferLocked(slot); // Clean up the slot first
971 mSlots[slot].mGraphicBuffer = buffers[i];
972 mSlots[slot].mFrameNumber = 0;
973 mSlots[slot].mFence = Fence::NO_FENCE;
974 BQ_LOGV("allocateBuffers: allocated a new buffer in slot %d", slot);
975 }
Dan Stoza29a3e902014-06-20 13:13:57 -0700976
Antoine Labour78014f32014-07-15 21:17:03 -0700977 mCore->mIsAllocating = false;
978 mCore->mIsAllocatingCondition.broadcast();
979 } // Autolock scope
Dan Stoza29a3e902014-06-20 13:13:57 -0700980 }
981}
982
Dan Stoza289ade12014-02-28 11:17:17 -0800983void BufferQueueProducer::binderDied(const wp<android::IBinder>& /* who */) {
984 // If we're here, it means that a producer we were connected to died.
985 // We're guaranteed that we are still connected to it because we remove
986 // this callback upon disconnect. It's therefore safe to read mConnectedApi
987 // without synchronization here.
988 int api = mCore->mConnectedApi;
989 disconnect(api);
990}
991
992} // namespace android