blob: cb8abdd992187c0de0b7b61da693df8537bc3758 [file] [log] [blame]
Daniel Lam70e80aa2012-01-22 15:26:27 -08001/*
2 * Copyright (C) 2012 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 "BufferQueue"
Daniel Lam6f15cc92012-01-22 15:26:27 -080018//#define LOG_NDEBUG 0
Jamie Gennisa85ca372012-02-23 19:27:23 -080019#define ATRACE_TAG ATRACE_TAG_GRAPHICS
Daniel Lam70e80aa2012-01-22 15:26:27 -080020
21#define GL_GLEXT_PROTOTYPES
22#define EGL_EGLEXT_PROTOTYPES
23
24#include <EGL/egl.h>
25#include <EGL/eglext.h>
26
27#include <gui/BufferQueue.h>
Mathias Agopian8335f1c2012-02-25 18:48:35 -080028#include <gui/ISurfaceComposer.h>
Daniel Lam70e80aa2012-01-22 15:26:27 -080029#include <private/gui/ComposerService.h>
Daniel Lam70e80aa2012-01-22 15:26:27 -080030
31#include <utils/Log.h>
Daniel Lam6f15cc92012-01-22 15:26:27 -080032#include <gui/SurfaceTexture.h>
Jamie Gennisa85ca372012-02-23 19:27:23 -080033#include <utils/Trace.h>
Daniel Lam70e80aa2012-01-22 15:26:27 -080034
35// This compile option causes SurfaceTexture to return the buffer that is currently
36// attached to the GL texture from dequeueBuffer when no other buffers are
37// available. It requires the drivers (Gralloc, GL, OMX IL, and Camera) to do
38// implicit cross-process synchronization to prevent the buffer from being
39// written to before the buffer has (a) been detached from the GL texture and
40// (b) all GL reads from the buffer have completed.
Daniel Lam6f15cc92012-01-22 15:26:27 -080041
42// During refactoring, do not support dequeuing the current buffer
43#undef ALLOW_DEQUEUE_CURRENT_BUFFER
44
Daniel Lam70e80aa2012-01-22 15:26:27 -080045#ifdef ALLOW_DEQUEUE_CURRENT_BUFFER
46#define FLAG_ALLOW_DEQUEUE_CURRENT_BUFFER true
47#warning "ALLOW_DEQUEUE_CURRENT_BUFFER enabled"
48#else
49#define FLAG_ALLOW_DEQUEUE_CURRENT_BUFFER false
50#endif
51
52// Macros for including the BufferQueue name in log messages
Daniel Lam6f15cc92012-01-22 15:26:27 -080053#define ST_LOGV(x, ...) ALOGV("[%s] "x, mConsumerName.string(), ##__VA_ARGS__)
54#define ST_LOGD(x, ...) ALOGD("[%s] "x, mConsumerName.string(), ##__VA_ARGS__)
55#define ST_LOGI(x, ...) ALOGI("[%s] "x, mConsumerName.string(), ##__VA_ARGS__)
56#define ST_LOGW(x, ...) ALOGW("[%s] "x, mConsumerName.string(), ##__VA_ARGS__)
57#define ST_LOGE(x, ...) ALOGE("[%s] "x, mConsumerName.string(), ##__VA_ARGS__)
Daniel Lam70e80aa2012-01-22 15:26:27 -080058
Mathias Agopiand1220b92012-03-01 22:11:25 -080059#define ATRACE_BUFFER_INDEX(index) \
60 char ___traceBuf[1024]; \
61 snprintf(___traceBuf, 1024, "%s: %d", mConsumerName.string(), (index)); \
62 android::ScopedTrace ___bufTracer(ATRACE_TAG, ___traceBuf);
63
Daniel Lam70e80aa2012-01-22 15:26:27 -080064namespace android {
65
66// Get an ID that's unique within this process.
67static int32_t createProcessUniqueId() {
68 static volatile int32_t globalCounter = 0;
69 return android_atomic_inc(&globalCounter);
70}
71
72BufferQueue::BufferQueue( bool allowSynchronousMode ) :
73 mDefaultWidth(1),
74 mDefaultHeight(1),
75 mPixelFormat(PIXEL_FORMAT_RGBA_8888),
76 mBufferCount(MIN_ASYNC_BUFFER_SLOTS),
77 mClientBufferCount(0),
78 mServerBufferCount(MIN_ASYNC_BUFFER_SLOTS),
Daniel Lam70e80aa2012-01-22 15:26:27 -080079 mNextTransform(0),
80 mNextScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
81 mSynchronousMode(false),
82 mAllowSynchronousMode(allowSynchronousMode),
83 mConnectedApi(NO_CONNECTED_API),
84 mAbandoned(false),
Daniel Lam6f15cc92012-01-22 15:26:27 -080085 mFrameCounter(0),
86 mBufferHasBeenQueued(false)
Daniel Lam70e80aa2012-01-22 15:26:27 -080087{
88 // Choose a name using the PID and a process-unique ID.
Daniel Lam6f15cc92012-01-22 15:26:27 -080089 mConsumerName = String8::format("unnamed-%d-%d", getpid(), createProcessUniqueId());
Daniel Lam70e80aa2012-01-22 15:26:27 -080090
91 ST_LOGV("BufferQueue");
92 sp<ISurfaceComposer> composer(ComposerService::getComposerService());
93 mGraphicBufferAlloc = composer->createGraphicBufferAlloc();
94 mNextCrop.makeInvalid();
95}
96
97BufferQueue::~BufferQueue() {
98 ST_LOGV("~BufferQueue");
99}
100
101status_t BufferQueue::setBufferCountServerLocked(int bufferCount) {
102 if (bufferCount > NUM_BUFFER_SLOTS)
103 return BAD_VALUE;
104
105 // special-case, nothing to do
106 if (bufferCount == mBufferCount)
107 return OK;
108
109 if (!mClientBufferCount &&
110 bufferCount >= mBufferCount) {
111 // easy, we just have more buffers
112 mBufferCount = bufferCount;
113 mServerBufferCount = bufferCount;
Mathias Agopian3e964c52012-03-06 18:26:54 -0800114 mDequeueCondition.broadcast();
Daniel Lam70e80aa2012-01-22 15:26:27 -0800115 } else {
116 // we're here because we're either
117 // - reducing the number of available buffers
118 // - or there is a client-buffer-count in effect
119
120 // less than 2 buffers is never allowed
121 if (bufferCount < 2)
122 return BAD_VALUE;
123
124 // when there is non client-buffer-count in effect, the client is not
125 // allowed to dequeue more than one buffer at a time,
126 // so the next time they dequeue a buffer, we know that they don't
127 // own one. the actual resizing will happen during the next
128 // dequeueBuffer.
129
130 mServerBufferCount = bufferCount;
131 }
132 return OK;
133}
134
Daniel Lam6f15cc92012-01-22 15:26:27 -0800135bool BufferQueue::isSynchronousMode() const {
136 Mutex::Autolock lock(mMutex);
137 return mSynchronousMode;
138}
139
140void BufferQueue::setConsumerName(const String8& name) {
141 Mutex::Autolock lock(mMutex);
142 mConsumerName = name;
143}
144
145void BufferQueue::setFrameAvailableListener(
146 const sp<FrameAvailableListener>& listener) {
147 ST_LOGV("setFrameAvailableListener");
148 Mutex::Autolock lock(mMutex);
149 mFrameAvailableListener = listener;
150}
151
Daniel Lam70e80aa2012-01-22 15:26:27 -0800152status_t BufferQueue::setBufferCount(int bufferCount) {
153 ST_LOGV("setBufferCount: count=%d", bufferCount);
154 Mutex::Autolock lock(mMutex);
155
156 if (mAbandoned) {
157 ST_LOGE("setBufferCount: SurfaceTexture has been abandoned!");
158 return NO_INIT;
159 }
160 if (bufferCount > NUM_BUFFER_SLOTS) {
161 ST_LOGE("setBufferCount: bufferCount larger than slots available");
162 return BAD_VALUE;
163 }
164
165 // Error out if the user has dequeued buffers
166 for (int i=0 ; i<mBufferCount ; i++) {
167 if (mSlots[i].mBufferState == BufferSlot::DEQUEUED) {
168 ST_LOGE("setBufferCount: client owns some buffers");
169 return -EINVAL;
170 }
171 }
172
173 const int minBufferSlots = mSynchronousMode ?
174 MIN_SYNC_BUFFER_SLOTS : MIN_ASYNC_BUFFER_SLOTS;
175 if (bufferCount == 0) {
176 mClientBufferCount = 0;
177 bufferCount = (mServerBufferCount >= minBufferSlots) ?
178 mServerBufferCount : minBufferSlots;
179 return setBufferCountServerLocked(bufferCount);
180 }
181
182 if (bufferCount < minBufferSlots) {
183 ST_LOGE("setBufferCount: requested buffer count (%d) is less than "
184 "minimum (%d)", bufferCount, minBufferSlots);
185 return BAD_VALUE;
186 }
187
188 // here we're guaranteed that the client doesn't have dequeued buffers
189 // and will release all of its buffer references.
190 freeAllBuffersLocked();
191 mBufferCount = bufferCount;
192 mClientBufferCount = bufferCount;
Daniel Lam6f15cc92012-01-22 15:26:27 -0800193 mBufferHasBeenQueued = false;
Daniel Lam70e80aa2012-01-22 15:26:27 -0800194 mQueue.clear();
Mathias Agopian3e964c52012-03-06 18:26:54 -0800195 mDequeueCondition.broadcast();
Daniel Lam70e80aa2012-01-22 15:26:27 -0800196 return OK;
197}
198
Daniel Lamf7c761e2012-01-30 15:51:27 -0800199int BufferQueue::query(int what, int* outValue)
200{
Jamie Gennisa85ca372012-02-23 19:27:23 -0800201 ATRACE_CALL();
Daniel Lamf7c761e2012-01-30 15:51:27 -0800202 Mutex::Autolock lock(mMutex);
203
204 if (mAbandoned) {
205 ST_LOGE("query: SurfaceTexture has been abandoned!");
206 return NO_INIT;
207 }
208
209 int value;
210 switch (what) {
211 case NATIVE_WINDOW_WIDTH:
212 value = mDefaultWidth;
213 break;
214 case NATIVE_WINDOW_HEIGHT:
215 value = mDefaultHeight;
216 break;
217 case NATIVE_WINDOW_FORMAT:
218 value = mPixelFormat;
219 break;
220 case NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS:
221 value = mSynchronousMode ?
222 (MIN_UNDEQUEUED_BUFFERS-1) : MIN_UNDEQUEUED_BUFFERS;
223 break;
224 default:
225 return BAD_VALUE;
226 }
227 outValue[0] = value;
228 return NO_ERROR;
229}
230
Daniel Lam70e80aa2012-01-22 15:26:27 -0800231status_t BufferQueue::requestBuffer(int slot, sp<GraphicBuffer>* buf) {
Jamie Gennisa85ca372012-02-23 19:27:23 -0800232 ATRACE_CALL();
Daniel Lam70e80aa2012-01-22 15:26:27 -0800233 ST_LOGV("requestBuffer: slot=%d", slot);
234 Mutex::Autolock lock(mMutex);
235 if (mAbandoned) {
236 ST_LOGE("requestBuffer: SurfaceTexture has been abandoned!");
237 return NO_INIT;
238 }
239 if (slot < 0 || mBufferCount <= slot) {
240 ST_LOGE("requestBuffer: slot index out of range [0, %d]: %d",
241 mBufferCount, slot);
242 return BAD_VALUE;
243 }
244 mSlots[slot].mRequestBufferCalled = true;
245 *buf = mSlots[slot].mGraphicBuffer;
246 return NO_ERROR;
247}
248
249status_t BufferQueue::dequeueBuffer(int *outBuf, uint32_t w, uint32_t h,
250 uint32_t format, uint32_t usage) {
Jamie Gennisa85ca372012-02-23 19:27:23 -0800251 ATRACE_CALL();
Daniel Lam70e80aa2012-01-22 15:26:27 -0800252 ST_LOGV("dequeueBuffer: w=%d h=%d fmt=%#x usage=%#x", w, h, format, usage);
253
254 if ((w && !h) || (!w && h)) {
255 ST_LOGE("dequeueBuffer: invalid size: w=%u, h=%u", w, h);
256 return BAD_VALUE;
257 }
258
259 status_t returnFlags(OK);
260 EGLDisplay dpy = EGL_NO_DISPLAY;
261 EGLSyncKHR fence = EGL_NO_SYNC_KHR;
262
263 { // Scope for the lock
264 Mutex::Autolock lock(mMutex);
265
266 int found = -1;
267 int foundSync = -1;
268 int dequeuedCount = 0;
269 bool tryAgain = true;
270 while (tryAgain) {
271 if (mAbandoned) {
272 ST_LOGE("dequeueBuffer: SurfaceTexture has been abandoned!");
273 return NO_INIT;
274 }
275
276 // We need to wait for the FIFO to drain if the number of buffer
277 // needs to change.
278 //
279 // The condition "number of buffers needs to change" is true if
280 // - the client doesn't care about how many buffers there are
281 // - AND the actual number of buffer is different from what was
282 // set in the last setBufferCountServer()
283 // - OR -
284 // setBufferCountServer() was set to a value incompatible with
285 // the synchronization mode (for instance because the sync mode
286 // changed since)
287 //
288 // As long as this condition is true AND the FIFO is not empty, we
289 // wait on mDequeueCondition.
290
291 const int minBufferCountNeeded = mSynchronousMode ?
292 MIN_SYNC_BUFFER_SLOTS : MIN_ASYNC_BUFFER_SLOTS;
293
294 const bool numberOfBuffersNeedsToChange = !mClientBufferCount &&
295 ((mServerBufferCount != mBufferCount) ||
296 (mServerBufferCount < minBufferCountNeeded));
297
298 if (!mQueue.isEmpty() && numberOfBuffersNeedsToChange) {
299 // wait for the FIFO to drain
300 mDequeueCondition.wait(mMutex);
301 // NOTE: we continue here because we need to reevaluate our
302 // whole state (eg: we could be abandoned or disconnected)
303 continue;
304 }
305
306 if (numberOfBuffersNeedsToChange) {
307 // here we're guaranteed that mQueue is empty
308 freeAllBuffersLocked();
Mathias Agopian3e964c52012-03-06 18:26:54 -0800309 // XXX: signal?
Daniel Lam70e80aa2012-01-22 15:26:27 -0800310 mBufferCount = mServerBufferCount;
311 if (mBufferCount < minBufferCountNeeded)
312 mBufferCount = minBufferCountNeeded;
Daniel Lam6f15cc92012-01-22 15:26:27 -0800313 mBufferHasBeenQueued = false;
Daniel Lam70e80aa2012-01-22 15:26:27 -0800314 returnFlags |= ISurfaceTexture::RELEASE_ALL_BUFFERS;
315 }
316
317 // look for a free buffer to give to the client
318 found = INVALID_BUFFER_SLOT;
319 foundSync = INVALID_BUFFER_SLOT;
320 dequeuedCount = 0;
321 for (int i = 0; i < mBufferCount; i++) {
322 const int state = mSlots[i].mBufferState;
323 if (state == BufferSlot::DEQUEUED) {
324 dequeuedCount++;
325 }
326
Daniel Lam6f15cc92012-01-22 15:26:27 -0800327 // this logic used to be if (FLAG_ALLOW_DEQUEUE_CURRENT_BUFFER)
328 // but dequeuing the current buffer is disabled.
329 if (false) {
330 // This functionality has been temporarily removed so
331 // BufferQueue and SurfaceTexture can be refactored into
332 // separate objects
Daniel Lam70e80aa2012-01-22 15:26:27 -0800333 } else {
334 if (state == BufferSlot::FREE) {
335 /* We return the oldest of the free buffers to avoid
336 * stalling the producer if possible. This is because
337 * the consumer may still have pending reads of the
338 * buffers in flight.
339 */
340 bool isOlder = mSlots[i].mFrameNumber <
341 mSlots[found].mFrameNumber;
342 if (found < 0 || isOlder) {
343 foundSync = i;
344 found = i;
345 }
346 }
347 }
348 }
349
350 // clients are not allowed to dequeue more than one buffer
351 // if they didn't set a buffer count.
352 if (!mClientBufferCount && dequeuedCount) {
353 ST_LOGE("dequeueBuffer: can't dequeue multiple buffers without "
354 "setting the buffer count");
355 return -EINVAL;
356 }
357
358 // See whether a buffer has been queued since the last
359 // setBufferCount so we know whether to perform the
360 // MIN_UNDEQUEUED_BUFFERS check below.
Daniel Lam6f15cc92012-01-22 15:26:27 -0800361 if (mBufferHasBeenQueued) {
Daniel Lam70e80aa2012-01-22 15:26:27 -0800362 // make sure the client is not trying to dequeue more buffers
363 // than allowed.
364 const int avail = mBufferCount - (dequeuedCount+1);
365 if (avail < (MIN_UNDEQUEUED_BUFFERS-int(mSynchronousMode))) {
366 ST_LOGE("dequeueBuffer: MIN_UNDEQUEUED_BUFFERS=%d exceeded "
367 "(dequeued=%d)",
368 MIN_UNDEQUEUED_BUFFERS-int(mSynchronousMode),
369 dequeuedCount);
370 return -EBUSY;
371 }
372 }
373
Daniel Lamc930cf32012-03-07 14:11:29 -0800374 // if no buffer is found, wait for a buffer to be released
375 tryAgain = found == INVALID_BUFFER_SLOT;
Daniel Lam70e80aa2012-01-22 15:26:27 -0800376 if (tryAgain) {
377 mDequeueCondition.wait(mMutex);
378 }
379 }
380
Daniel Lam70e80aa2012-01-22 15:26:27 -0800381
382 if (found == INVALID_BUFFER_SLOT) {
383 // This should not happen.
384 ST_LOGE("dequeueBuffer: no available buffer slots");
385 return -EBUSY;
386 }
387
388 const int buf = found;
389 *outBuf = found;
390
Mathias Agopiand1220b92012-03-01 22:11:25 -0800391 ATRACE_BUFFER_INDEX(buf);
392
Daniel Lam70e80aa2012-01-22 15:26:27 -0800393 const bool useDefaultSize = !w && !h;
394 if (useDefaultSize) {
395 // use the default size
396 w = mDefaultWidth;
397 h = mDefaultHeight;
398 }
399
400 const bool updateFormat = (format != 0);
401 if (!updateFormat) {
402 // keep the current (or default) format
403 format = mPixelFormat;
404 }
405
406 // buffer is now in DEQUEUED (but can also be current at the same time,
407 // if we're in synchronous mode)
408 mSlots[buf].mBufferState = BufferSlot::DEQUEUED;
409
410 const sp<GraphicBuffer>& buffer(mSlots[buf].mGraphicBuffer);
411 if ((buffer == NULL) ||
412 (uint32_t(buffer->width) != w) ||
413 (uint32_t(buffer->height) != h) ||
414 (uint32_t(buffer->format) != format) ||
415 ((uint32_t(buffer->usage) & usage) != usage))
416 {
417 usage |= GraphicBuffer::USAGE_HW_TEXTURE;
418 status_t error;
419 sp<GraphicBuffer> graphicBuffer(
420 mGraphicBufferAlloc->createGraphicBuffer(
421 w, h, format, usage, &error));
422 if (graphicBuffer == 0) {
423 ST_LOGE("dequeueBuffer: SurfaceComposer::createGraphicBuffer "
424 "failed");
425 return error;
426 }
427 if (updateFormat) {
428 mPixelFormat = format;
429 }
Daniel Lam6f15cc92012-01-22 15:26:27 -0800430
431 mSlots[buf].mAcquireCalled = false;
Daniel Lam70e80aa2012-01-22 15:26:27 -0800432 mSlots[buf].mGraphicBuffer = graphicBuffer;
433 mSlots[buf].mRequestBufferCalled = false;
434 mSlots[buf].mFence = EGL_NO_SYNC_KHR;
Daniel Lam6f15cc92012-01-22 15:26:27 -0800435 mSlots[buf].mEglDisplay = EGL_NO_DISPLAY;
436
437
438
439
Daniel Lam70e80aa2012-01-22 15:26:27 -0800440 returnFlags |= ISurfaceTexture::BUFFER_NEEDS_REALLOCATION;
441 }
442
443 dpy = mSlots[buf].mEglDisplay;
444 fence = mSlots[buf].mFence;
445 mSlots[buf].mFence = EGL_NO_SYNC_KHR;
Daniel Lam6f15cc92012-01-22 15:26:27 -0800446 } // end lock scope
Daniel Lam70e80aa2012-01-22 15:26:27 -0800447
448 if (fence != EGL_NO_SYNC_KHR) {
449 EGLint result = eglClientWaitSyncKHR(dpy, fence, 0, 1000000000);
450 // If something goes wrong, log the error, but return the buffer without
451 // synchronizing access to it. It's too late at this point to abort the
452 // dequeue operation.
453 if (result == EGL_FALSE) {
454 ALOGE("dequeueBuffer: error waiting for fence: %#x", eglGetError());
455 } else if (result == EGL_TIMEOUT_EXPIRED_KHR) {
456 ALOGE("dequeueBuffer: timeout waiting for fence");
457 }
458 eglDestroySyncKHR(dpy, fence);
Daniel Lam6f15cc92012-01-22 15:26:27 -0800459
Daniel Lam70e80aa2012-01-22 15:26:27 -0800460 }
461
462 ST_LOGV("dequeueBuffer: returning slot=%d buf=%p flags=%#x", *outBuf,
463 mSlots[*outBuf].mGraphicBuffer->handle, returnFlags);
464
465 return returnFlags;
466}
467
468status_t BufferQueue::setSynchronousMode(bool enabled) {
Jamie Gennisa85ca372012-02-23 19:27:23 -0800469 ATRACE_CALL();
Daniel Lam70e80aa2012-01-22 15:26:27 -0800470 ST_LOGV("setSynchronousMode: enabled=%d", enabled);
471 Mutex::Autolock lock(mMutex);
472
473 if (mAbandoned) {
474 ST_LOGE("setSynchronousMode: SurfaceTexture has been abandoned!");
475 return NO_INIT;
476 }
477
478 status_t err = OK;
479 if (!mAllowSynchronousMode && enabled)
480 return err;
481
482 if (!enabled) {
483 // going to asynchronous mode, drain the queue
484 err = drainQueueLocked();
485 if (err != NO_ERROR)
486 return err;
487 }
488
489 if (mSynchronousMode != enabled) {
490 // - if we're going to asynchronous mode, the queue is guaranteed to be
491 // empty here
492 // - if the client set the number of buffers, we're guaranteed that
493 // we have at least 3 (because we don't allow less)
494 mSynchronousMode = enabled;
Mathias Agopian3e964c52012-03-06 18:26:54 -0800495 mDequeueCondition.broadcast();
Daniel Lam70e80aa2012-01-22 15:26:27 -0800496 }
497 return err;
498}
499
500status_t BufferQueue::queueBuffer(int buf, int64_t timestamp,
501 uint32_t* outWidth, uint32_t* outHeight, uint32_t* outTransform) {
Jamie Gennisa85ca372012-02-23 19:27:23 -0800502 ATRACE_CALL();
Mathias Agopiand1220b92012-03-01 22:11:25 -0800503 ATRACE_BUFFER_INDEX(buf);
504
Daniel Lam70e80aa2012-01-22 15:26:27 -0800505 ST_LOGV("queueBuffer: slot=%d time=%lld", buf, timestamp);
506
507 sp<FrameAvailableListener> listener;
508
509 { // scope for the lock
510 Mutex::Autolock lock(mMutex);
511 if (mAbandoned) {
512 ST_LOGE("queueBuffer: SurfaceTexture has been abandoned!");
513 return NO_INIT;
514 }
515 if (buf < 0 || buf >= mBufferCount) {
516 ST_LOGE("queueBuffer: slot index out of range [0, %d]: %d",
517 mBufferCount, buf);
518 return -EINVAL;
519 } else if (mSlots[buf].mBufferState != BufferSlot::DEQUEUED) {
520 ST_LOGE("queueBuffer: slot %d is not owned by the client "
521 "(state=%d)", buf, mSlots[buf].mBufferState);
522 return -EINVAL;
Daniel Lam70e80aa2012-01-22 15:26:27 -0800523 } else if (!mSlots[buf].mRequestBufferCalled) {
524 ST_LOGE("queueBuffer: slot %d was enqueued without requesting a "
525 "buffer", buf);
526 return -EINVAL;
527 }
528
529 if (mSynchronousMode) {
530 // In synchronous mode we queue all buffers in a FIFO.
531 mQueue.push_back(buf);
532
533 // Synchronous mode always signals that an additional frame should
534 // be consumed.
535 listener = mFrameAvailableListener;
536 } else {
537 // In asynchronous mode we only keep the most recent buffer.
538 if (mQueue.empty()) {
539 mQueue.push_back(buf);
540
541 // Asynchronous mode only signals that a frame should be
542 // consumed if no previous frame was pending. If a frame were
543 // pending then the consumer would have already been notified.
544 listener = mFrameAvailableListener;
545 } else {
546 Fifo::iterator front(mQueue.begin());
547 // buffer currently queued is freed
548 mSlots[*front].mBufferState = BufferSlot::FREE;
549 // and we record the new buffer index in the queued list
550 *front = buf;
551 }
552 }
553
554 mSlots[buf].mBufferState = BufferSlot::QUEUED;
555 mSlots[buf].mCrop = mNextCrop;
556 mSlots[buf].mTransform = mNextTransform;
557 mSlots[buf].mScalingMode = mNextScalingMode;
558 mSlots[buf].mTimestamp = timestamp;
559 mFrameCounter++;
560 mSlots[buf].mFrameNumber = mFrameCounter;
561
Daniel Lam6f15cc92012-01-22 15:26:27 -0800562 mBufferHasBeenQueued = true;
Mathias Agopian3e964c52012-03-06 18:26:54 -0800563 mDequeueCondition.broadcast();
Daniel Lam70e80aa2012-01-22 15:26:27 -0800564
565 *outWidth = mDefaultWidth;
566 *outHeight = mDefaultHeight;
567 *outTransform = 0;
Jamie Gennisa85ca372012-02-23 19:27:23 -0800568
569 ATRACE_INT(mConsumerName.string(), mQueue.size());
Daniel Lam70e80aa2012-01-22 15:26:27 -0800570 } // scope for the lock
571
572 // call back without lock held
573 if (listener != 0) {
574 listener->onFrameAvailable();
575 }
576 return OK;
577}
578
579void BufferQueue::cancelBuffer(int buf) {
Jamie Gennisa85ca372012-02-23 19:27:23 -0800580 ATRACE_CALL();
Daniel Lam70e80aa2012-01-22 15:26:27 -0800581 ST_LOGV("cancelBuffer: slot=%d", buf);
582 Mutex::Autolock lock(mMutex);
583
584 if (mAbandoned) {
585 ST_LOGW("cancelBuffer: BufferQueue has been abandoned!");
586 return;
587 }
588
589 if (buf < 0 || buf >= mBufferCount) {
590 ST_LOGE("cancelBuffer: slot index out of range [0, %d]: %d",
591 mBufferCount, buf);
592 return;
593 } else if (mSlots[buf].mBufferState != BufferSlot::DEQUEUED) {
594 ST_LOGE("cancelBuffer: slot %d is not owned by the client (state=%d)",
595 buf, mSlots[buf].mBufferState);
596 return;
597 }
598 mSlots[buf].mBufferState = BufferSlot::FREE;
599 mSlots[buf].mFrameNumber = 0;
Mathias Agopian3e964c52012-03-06 18:26:54 -0800600 mDequeueCondition.broadcast();
Daniel Lam70e80aa2012-01-22 15:26:27 -0800601}
602
603status_t BufferQueue::setCrop(const Rect& crop) {
Jamie Gennisa85ca372012-02-23 19:27:23 -0800604 ATRACE_CALL();
Daniel Lam70e80aa2012-01-22 15:26:27 -0800605 ST_LOGV("setCrop: crop=[%d,%d,%d,%d]", crop.left, crop.top, crop.right,
606 crop.bottom);
607
608 Mutex::Autolock lock(mMutex);
609 if (mAbandoned) {
610 ST_LOGE("setCrop: BufferQueue has been abandoned!");
611 return NO_INIT;
612 }
613 mNextCrop = crop;
614 return OK;
615}
616
617status_t BufferQueue::setTransform(uint32_t transform) {
Jamie Gennisa85ca372012-02-23 19:27:23 -0800618 ATRACE_CALL();
Daniel Lam70e80aa2012-01-22 15:26:27 -0800619 ST_LOGV("setTransform: xform=%#x", transform);
620 Mutex::Autolock lock(mMutex);
621 if (mAbandoned) {
622 ST_LOGE("setTransform: BufferQueue has been abandoned!");
623 return NO_INIT;
624 }
625 mNextTransform = transform;
626 return OK;
627}
628
629status_t BufferQueue::setScalingMode(int mode) {
Jamie Gennisa85ca372012-02-23 19:27:23 -0800630 ATRACE_CALL();
Daniel Lam70e80aa2012-01-22 15:26:27 -0800631 ST_LOGV("setScalingMode: mode=%d", mode);
632
633 switch (mode) {
634 case NATIVE_WINDOW_SCALING_MODE_FREEZE:
635 case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW:
636 break;
637 default:
638 ST_LOGE("unknown scaling mode: %d", mode);
639 return BAD_VALUE;
640 }
641
642 Mutex::Autolock lock(mMutex);
643 mNextScalingMode = mode;
644 return OK;
645}
646
647status_t BufferQueue::connect(int api,
648 uint32_t* outWidth, uint32_t* outHeight, uint32_t* outTransform) {
Jamie Gennisa85ca372012-02-23 19:27:23 -0800649 ATRACE_CALL();
Daniel Lam70e80aa2012-01-22 15:26:27 -0800650 ST_LOGV("connect: api=%d", api);
651 Mutex::Autolock lock(mMutex);
652
653 if (mAbandoned) {
654 ST_LOGE("connect: BufferQueue has been abandoned!");
655 return NO_INIT;
656 }
657
658 int err = NO_ERROR;
659 switch (api) {
660 case NATIVE_WINDOW_API_EGL:
661 case NATIVE_WINDOW_API_CPU:
662 case NATIVE_WINDOW_API_MEDIA:
663 case NATIVE_WINDOW_API_CAMERA:
664 if (mConnectedApi != NO_CONNECTED_API) {
665 ST_LOGE("connect: already connected (cur=%d, req=%d)",
666 mConnectedApi, api);
667 err = -EINVAL;
668 } else {
669 mConnectedApi = api;
670 *outWidth = mDefaultWidth;
671 *outHeight = mDefaultHeight;
672 *outTransform = 0;
673 }
674 break;
675 default:
676 err = -EINVAL;
677 break;
678 }
Daniel Lam6f15cc92012-01-22 15:26:27 -0800679
680 mBufferHasBeenQueued = false;
681
Daniel Lam70e80aa2012-01-22 15:26:27 -0800682 return err;
683}
684
685status_t BufferQueue::disconnect(int api) {
Jamie Gennisa85ca372012-02-23 19:27:23 -0800686 ATRACE_CALL();
Daniel Lam70e80aa2012-01-22 15:26:27 -0800687 ST_LOGV("disconnect: api=%d", api);
688 Mutex::Autolock lock(mMutex);
689
690 if (mAbandoned) {
691 // it is not really an error to disconnect after the surface
692 // has been abandoned, it should just be a no-op.
693 return NO_ERROR;
694 }
695
696 int err = NO_ERROR;
697 switch (api) {
698 case NATIVE_WINDOW_API_EGL:
699 case NATIVE_WINDOW_API_CPU:
700 case NATIVE_WINDOW_API_MEDIA:
701 case NATIVE_WINDOW_API_CAMERA:
702 if (mConnectedApi == api) {
703 drainQueueAndFreeBuffersLocked();
704 mConnectedApi = NO_CONNECTED_API;
705 mNextCrop.makeInvalid();
706 mNextScalingMode = NATIVE_WINDOW_SCALING_MODE_FREEZE;
707 mNextTransform = 0;
Mathias Agopian3e964c52012-03-06 18:26:54 -0800708 mDequeueCondition.broadcast();
Daniel Lam70e80aa2012-01-22 15:26:27 -0800709 } else {
710 ST_LOGE("disconnect: connected to another api (cur=%d, req=%d)",
711 mConnectedApi, api);
712 err = -EINVAL;
713 }
714 break;
715 default:
716 ST_LOGE("disconnect: unknown API %d", api);
717 err = -EINVAL;
718 break;
719 }
720 return err;
721}
722
Daniel Lam6f15cc92012-01-22 15:26:27 -0800723void BufferQueue::dump(String8& result) const
724{
725 char buffer[1024];
726 BufferQueue::dump(result, "", buffer, 1024);
727}
728
729void BufferQueue::dump(String8& result, const char* prefix,
730 char* buffer, size_t SIZE) const
731{
732 Mutex::Autolock _l(mMutex);
733 snprintf(buffer, SIZE,
734 "%snext : {crop=[%d,%d,%d,%d], transform=0x%02x}\n"
735 ,prefix, mNextCrop.left, mNextCrop.top, mNextCrop.right,
736 mNextCrop.bottom, mNextTransform
737 );
738 result.append(buffer);
739
740 String8 fifo;
741 int fifoSize = 0;
742 Fifo::const_iterator i(mQueue.begin());
743 while (i != mQueue.end()) {
744 snprintf(buffer, SIZE, "%02d ", *i++);
745 fifoSize++;
746 fifo.append(buffer);
747 }
748
749 snprintf(buffer, SIZE,
750 "%s-BufferQueue mBufferCount=%d, mSynchronousMode=%d, default-size=[%dx%d], "
751 "mPixelFormat=%d, FIFO(%d)={%s}\n",
752 prefix, mBufferCount, mSynchronousMode, mDefaultWidth,
753 mDefaultHeight, mPixelFormat, fifoSize, fifo.string());
754 result.append(buffer);
755
756
757 struct {
758 const char * operator()(int state) const {
759 switch (state) {
760 case BufferSlot::DEQUEUED: return "DEQUEUED";
761 case BufferSlot::QUEUED: return "QUEUED";
762 case BufferSlot::FREE: return "FREE";
763 case BufferSlot::ACQUIRED: return "ACQUIRED";
764 default: return "Unknown";
765 }
766 }
767 } stateName;
768
769 for (int i=0 ; i<mBufferCount ; i++) {
770 const BufferSlot& slot(mSlots[i]);
771 snprintf(buffer, SIZE,
772 "%s%s[%02d] "
773 "state=%-8s, crop=[%d,%d,%d,%d], "
774 "transform=0x%02x, timestamp=%lld",
775 prefix, (slot.mBufferState == BufferSlot::ACQUIRED)?">":" ", i,
776 stateName(slot.mBufferState),
777 slot.mCrop.left, slot.mCrop.top, slot.mCrop.right,
778 slot.mCrop.bottom, slot.mTransform, slot.mTimestamp
779 );
780 result.append(buffer);
781
782 const sp<GraphicBuffer>& buf(slot.mGraphicBuffer);
783 if (buf != NULL) {
784 snprintf(buffer, SIZE,
785 ", %p [%4ux%4u:%4u,%3X]",
786 buf->handle, buf->width, buf->height, buf->stride,
787 buf->format);
788 result.append(buffer);
789 }
790 result.append("\n");
791 }
792}
793
Daniel Lam70e80aa2012-01-22 15:26:27 -0800794void BufferQueue::freeBufferLocked(int i) {
795 mSlots[i].mGraphicBuffer = 0;
796 mSlots[i].mBufferState = BufferSlot::FREE;
797 mSlots[i].mFrameNumber = 0;
Daniel Lam6f15cc92012-01-22 15:26:27 -0800798 mSlots[i].mAcquireCalled = false;
799
800 // destroy fence as BufferQueue now takes ownership
801 if (mSlots[i].mFence != EGL_NO_SYNC_KHR) {
802 eglDestroySyncKHR(mSlots[i].mEglDisplay, mSlots[i].mFence);
803 mSlots[i].mFence = EGL_NO_SYNC_KHR;
Daniel Lam70e80aa2012-01-22 15:26:27 -0800804 }
805}
806
807void BufferQueue::freeAllBuffersLocked() {
808 ALOGW_IF(!mQueue.isEmpty(),
809 "freeAllBuffersLocked called but mQueue is not empty");
Daniel Lam6f15cc92012-01-22 15:26:27 -0800810 mQueue.clear();
811 mBufferHasBeenQueued = false;
Daniel Lam70e80aa2012-01-22 15:26:27 -0800812 for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
813 freeBufferLocked(i);
814 }
815}
816
Daniel Lam6f15cc92012-01-22 15:26:27 -0800817status_t BufferQueue::acquire(BufferItem *buffer) {
Mathias Agopiand1220b92012-03-01 22:11:25 -0800818 ATRACE_CALL();
Daniel Lam6f15cc92012-01-22 15:26:27 -0800819 Mutex::Autolock _l(mMutex);
820 // check if queue is empty
821 // In asynchronous mode the list is guaranteed to be one buffer
822 // deep, while in synchronous mode we use the oldest buffer.
823 if (!mQueue.empty()) {
824 Fifo::iterator front(mQueue.begin());
825 int buf = *front;
826
Mathias Agopiand1220b92012-03-01 22:11:25 -0800827 ATRACE_BUFFER_INDEX(buf);
828
Daniel Lam6f15cc92012-01-22 15:26:27 -0800829 if (mSlots[buf].mAcquireCalled) {
830 buffer->mGraphicBuffer = NULL;
831 }
832 else {
833 buffer->mGraphicBuffer = mSlots[buf].mGraphicBuffer;
834 }
835 buffer->mCrop = mSlots[buf].mCrop;
836 buffer->mTransform = mSlots[buf].mTransform;
837 buffer->mScalingMode = mSlots[buf].mScalingMode;
838 buffer->mFrameNumber = mSlots[buf].mFrameNumber;
Daniel Lamd137cc72012-03-02 10:17:34 -0800839 buffer->mTimestamp = mSlots[buf].mTimestamp;
Daniel Lam6f15cc92012-01-22 15:26:27 -0800840 buffer->mBuf = buf;
841 mSlots[buf].mAcquireCalled = true;
842
843 mSlots[buf].mBufferState = BufferSlot::ACQUIRED;
844 mQueue.erase(front);
Mathias Agopian3e964c52012-03-06 18:26:54 -0800845 mDequeueCondition.broadcast();
Jamie Gennisa85ca372012-02-23 19:27:23 -0800846
847 ATRACE_INT(mConsumerName.string(), mQueue.size());
Daniel Lam6f15cc92012-01-22 15:26:27 -0800848 }
849 else {
850 return -EINVAL; //should be a better return code
851 }
852
853 return OK;
854}
855
856status_t BufferQueue::releaseBuffer(int buf, EGLDisplay display,
857 EGLSyncKHR fence) {
Mathias Agopiand1220b92012-03-01 22:11:25 -0800858 ATRACE_CALL();
859 ATRACE_BUFFER_INDEX(buf);
860
Daniel Lam6f15cc92012-01-22 15:26:27 -0800861 Mutex::Autolock _l(mMutex);
862
863 if (buf == INVALID_BUFFER_SLOT) {
864 return -EINVAL;
865 }
866
867 mSlots[buf].mEglDisplay = display;
868 mSlots[buf].mFence = fence;
869
870 // The current buffer becomes FREE if it was still in the queued
871 // state. If it has already been given to the client
872 // (synchronous mode), then it stays in DEQUEUED state.
873 if (mSlots[buf].mBufferState == BufferSlot::QUEUED
874 || mSlots[buf].mBufferState == BufferSlot::ACQUIRED) {
875 mSlots[buf].mBufferState = BufferSlot::FREE;
876 }
Mathias Agopian3e964c52012-03-06 18:26:54 -0800877
878 mDequeueCondition.broadcast();
Daniel Lam6f15cc92012-01-22 15:26:27 -0800879
880 return OK;
881}
882
883status_t BufferQueue::consumerDisconnect() {
884 Mutex::Autolock lock(mMutex);
885 // Once the SurfaceTexture disconnects, the BufferQueue
886 // is considered abandoned
887 mAbandoned = true;
888 freeAllBuffersLocked();
Mathias Agopian3e964c52012-03-06 18:26:54 -0800889 mDequeueCondition.broadcast();
Daniel Lam6f15cc92012-01-22 15:26:27 -0800890 return OK;
891}
892
893status_t BufferQueue::setDefaultBufferSize(uint32_t w, uint32_t h)
894{
895 ST_LOGV("setDefaultBufferSize: w=%d, h=%d", w, h);
896 if (!w || !h) {
897 ST_LOGE("setDefaultBufferSize: dimensions cannot be 0 (w=%d, h=%d)",
898 w, h);
899 return BAD_VALUE;
900 }
901
902 Mutex::Autolock lock(mMutex);
903 mDefaultWidth = w;
904 mDefaultHeight = h;
905 return OK;
906}
907
908status_t BufferQueue::setBufferCountServer(int bufferCount) {
Jamie Gennisa85ca372012-02-23 19:27:23 -0800909 ATRACE_CALL();
Daniel Lam6f15cc92012-01-22 15:26:27 -0800910 Mutex::Autolock lock(mMutex);
911 return setBufferCountServerLocked(bufferCount);
912}
913
Daniel Lam70e80aa2012-01-22 15:26:27 -0800914void BufferQueue::freeAllBuffersExceptHeadLocked() {
915 ALOGW_IF(!mQueue.isEmpty(),
916 "freeAllBuffersExceptCurrentLocked called but mQueue is not empty");
917 int head = -1;
918 if (!mQueue.empty()) {
919 Fifo::iterator front(mQueue.begin());
920 head = *front;
921 }
Daniel Lam6f15cc92012-01-22 15:26:27 -0800922 mBufferHasBeenQueued = false;
Daniel Lam70e80aa2012-01-22 15:26:27 -0800923 for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
924 if (i != head) {
925 freeBufferLocked(i);
926 }
927 }
928}
929
930status_t BufferQueue::drainQueueLocked() {
931 while (mSynchronousMode && !mQueue.isEmpty()) {
932 mDequeueCondition.wait(mMutex);
933 if (mAbandoned) {
934 ST_LOGE("drainQueueLocked: BufferQueue has been abandoned!");
935 return NO_INIT;
936 }
937 if (mConnectedApi == NO_CONNECTED_API) {
938 ST_LOGE("drainQueueLocked: BufferQueue is not connected!");
939 return NO_INIT;
940 }
941 }
942 return NO_ERROR;
943}
944
945status_t BufferQueue::drainQueueAndFreeBuffersLocked() {
946 status_t err = drainQueueLocked();
947 if (err == NO_ERROR) {
948 if (mSynchronousMode) {
949 freeAllBuffersLocked();
950 } else {
951 freeAllBuffersExceptHeadLocked();
952 }
953 }
954 return err;
955}
956
957}; // namespace android