OSDN Git Service

Make ANW.setSwapInterval(0) work again
[android-x86/frameworks-native.git] / libs / gui / BufferQueue.cpp
1 /*
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"
18 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
19 //#define LOG_NDEBUG 0
20
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>
28 #include <gui/ISurfaceComposer.h>
29 #include <private/gui/ComposerService.h>
30
31 #include <utils/Log.h>
32 #include <utils/Trace.h>
33 #include <utils/CallStack.h>
34
35 // Macros for including the BufferQueue name in log messages
36 #define ST_LOGV(x, ...) ALOGV("[%s] "x, mConsumerName.string(), ##__VA_ARGS__)
37 #define ST_LOGD(x, ...) ALOGD("[%s] "x, mConsumerName.string(), ##__VA_ARGS__)
38 #define ST_LOGI(x, ...) ALOGI("[%s] "x, mConsumerName.string(), ##__VA_ARGS__)
39 #define ST_LOGW(x, ...) ALOGW("[%s] "x, mConsumerName.string(), ##__VA_ARGS__)
40 #define ST_LOGE(x, ...) ALOGE("[%s] "x, mConsumerName.string(), ##__VA_ARGS__)
41
42 #define ATRACE_BUFFER_INDEX(index)                                            \
43     if (ATRACE_ENABLED()) {                                                   \
44         char ___traceBuf[1024];                                               \
45         snprintf(___traceBuf, 1024, "%s: %d", mConsumerName.string(),         \
46                 (index));                                                     \
47         android::ScopedTrace ___bufTracer(ATRACE_TAG, ___traceBuf);           \
48     }
49
50 namespace android {
51
52 // Get an ID that's unique within this process.
53 static int32_t createProcessUniqueId() {
54     static volatile int32_t globalCounter = 0;
55     return android_atomic_inc(&globalCounter);
56 }
57
58 static const char* scalingModeName(int scalingMode) {
59     switch (scalingMode) {
60         case NATIVE_WINDOW_SCALING_MODE_FREEZE: return "FREEZE";
61         case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW: return "SCALE_TO_WINDOW";
62         case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP: return "SCALE_CROP";
63         default: return "Unknown";
64     }
65 }
66
67 BufferQueue::BufferQueue(const sp<IGraphicBufferAlloc>& allocator) :
68     mDefaultWidth(1),
69     mDefaultHeight(1),
70     mMaxAcquiredBufferCount(1),
71     mDefaultMaxBufferCount(2),
72     mOverrideMaxBufferCount(0),
73     mConsumerControlledByApp(false),
74     mDequeueBufferCannotBlock(false),
75     mConnectedApi(NO_CONNECTED_API),
76     mAbandoned(false),
77     mFrameCounter(0),
78     mBufferHasBeenQueued(false),
79     mDefaultBufferFormat(PIXEL_FORMAT_RGBA_8888),
80     mConsumerUsageBits(0),
81     mTransformHint(0)
82 {
83     // Choose a name using the PID and a process-unique ID.
84     mConsumerName = String8::format("unnamed-%d-%d", getpid(), createProcessUniqueId());
85
86     ST_LOGV("BufferQueue");
87     if (allocator == NULL) {
88         sp<ISurfaceComposer> composer(ComposerService::getComposerService());
89         mGraphicBufferAlloc = composer->createGraphicBufferAlloc();
90         if (mGraphicBufferAlloc == 0) {
91             ST_LOGE("createGraphicBufferAlloc() failed in BufferQueue()");
92         }
93     } else {
94         mGraphicBufferAlloc = allocator;
95     }
96 }
97
98 BufferQueue::~BufferQueue() {
99     ST_LOGV("~BufferQueue");
100 }
101
102 status_t BufferQueue::setDefaultMaxBufferCountLocked(int count) {
103     if (count < 2 || count > NUM_BUFFER_SLOTS)
104         return BAD_VALUE;
105
106     mDefaultMaxBufferCount = count;
107     mDequeueCondition.broadcast();
108
109     return NO_ERROR;
110 }
111
112 void BufferQueue::setConsumerName(const String8& name) {
113     Mutex::Autolock lock(mMutex);
114     mConsumerName = name;
115 }
116
117 status_t BufferQueue::setDefaultBufferFormat(uint32_t defaultFormat) {
118     Mutex::Autolock lock(mMutex);
119     mDefaultBufferFormat = defaultFormat;
120     return NO_ERROR;
121 }
122
123 status_t BufferQueue::setConsumerUsageBits(uint32_t usage) {
124     Mutex::Autolock lock(mMutex);
125     mConsumerUsageBits = usage;
126     return NO_ERROR;
127 }
128
129 status_t BufferQueue::setTransformHint(uint32_t hint) {
130     ST_LOGV("setTransformHint: %02x", hint);
131     Mutex::Autolock lock(mMutex);
132     mTransformHint = hint;
133     return NO_ERROR;
134 }
135
136 status_t BufferQueue::setBufferCount(int bufferCount) {
137     ST_LOGV("setBufferCount: count=%d", bufferCount);
138
139     sp<ConsumerListener> listener;
140     {
141         Mutex::Autolock lock(mMutex);
142
143         if (mAbandoned) {
144             ST_LOGE("setBufferCount: BufferQueue has been abandoned!");
145             return NO_INIT;
146         }
147         if (bufferCount > NUM_BUFFER_SLOTS) {
148             ST_LOGE("setBufferCount: bufferCount too large (max %d)",
149                     NUM_BUFFER_SLOTS);
150             return BAD_VALUE;
151         }
152
153         // Error out if the user has dequeued buffers
154         for (int i=0 ; i<NUM_BUFFER_SLOTS; i++) {
155             if (mSlots[i].mBufferState == BufferSlot::DEQUEUED) {
156                 ST_LOGE("setBufferCount: client owns some buffers");
157                 return -EINVAL;
158             }
159         }
160
161         if (bufferCount == 0) {
162             mOverrideMaxBufferCount = 0;
163             mDequeueCondition.broadcast();
164             return NO_ERROR;
165         }
166
167         // fine to assume async to false before we're setting the buffer count
168         const int minBufferSlots = getMinMaxBufferCountLocked(false);
169         if (bufferCount < minBufferSlots) {
170             ST_LOGE("setBufferCount: requested buffer count (%d) is less than "
171                     "minimum (%d)", bufferCount, minBufferSlots);
172             return BAD_VALUE;
173         }
174
175         // here we're guaranteed that the client doesn't have dequeued buffers
176         // and will release all of its buffer references.  We don't clear the
177         // queue, however, so currently queued buffers still get displayed.
178         freeAllBuffersLocked();
179         mOverrideMaxBufferCount = bufferCount;
180         mDequeueCondition.broadcast();
181         listener = mConsumerListener;
182     } // scope for lock
183
184     if (listener != NULL) {
185         listener->onBuffersReleased();
186     }
187
188     return NO_ERROR;
189 }
190
191 int BufferQueue::query(int what, int* outValue)
192 {
193     ATRACE_CALL();
194     Mutex::Autolock lock(mMutex);
195
196     if (mAbandoned) {
197         ST_LOGE("query: BufferQueue has been abandoned!");
198         return NO_INIT;
199     }
200
201     int value;
202     switch (what) {
203     case NATIVE_WINDOW_WIDTH:
204         value = mDefaultWidth;
205         break;
206     case NATIVE_WINDOW_HEIGHT:
207         value = mDefaultHeight;
208         break;
209     case NATIVE_WINDOW_FORMAT:
210         value = mDefaultBufferFormat;
211         break;
212     case NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS:
213         value = getMinUndequeuedBufferCount(false);
214         break;
215     case NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND:
216         value = (mQueue.size() >= 2);
217         break;
218     default:
219         return BAD_VALUE;
220     }
221     outValue[0] = value;
222     return NO_ERROR;
223 }
224
225 status_t BufferQueue::requestBuffer(int slot, sp<GraphicBuffer>* buf) {
226     ATRACE_CALL();
227     ST_LOGV("requestBuffer: slot=%d", slot);
228     Mutex::Autolock lock(mMutex);
229     if (mAbandoned) {
230         ST_LOGE("requestBuffer: BufferQueue has been abandoned!");
231         return NO_INIT;
232     }
233     if (slot < 0 || slot >= NUM_BUFFER_SLOTS) {
234         ST_LOGE("requestBuffer: slot index out of range [0, %d]: %d",
235                 NUM_BUFFER_SLOTS, slot);
236         return BAD_VALUE;
237     } else if (mSlots[slot].mBufferState != BufferSlot::DEQUEUED) {
238         ST_LOGE("requestBuffer: slot %d is not owned by the client (state=%d)",
239                 slot, mSlots[slot].mBufferState);
240         return BAD_VALUE;
241     }
242     mSlots[slot].mRequestBufferCalled = true;
243     *buf = mSlots[slot].mGraphicBuffer;
244     return NO_ERROR;
245 }
246
247 status_t BufferQueue::dequeueBuffer(int *outBuf, sp<Fence>* outFence, bool async,
248         uint32_t w, uint32_t h, uint32_t format, uint32_t usage) {
249     ATRACE_CALL();
250     ST_LOGV("dequeueBuffer: w=%d h=%d fmt=%#x usage=%#x", w, h, format, usage);
251
252     if ((w && !h) || (!w && h)) {
253         ST_LOGE("dequeueBuffer: invalid size: w=%u, h=%u", w, h);
254         return BAD_VALUE;
255     }
256
257     status_t returnFlags(OK);
258     EGLDisplay dpy = EGL_NO_DISPLAY;
259     EGLSyncKHR eglFence = EGL_NO_SYNC_KHR;
260
261     { // Scope for the lock
262         Mutex::Autolock lock(mMutex);
263
264         if (format == 0) {
265             format = mDefaultBufferFormat;
266         }
267         // turn on usage bits the consumer requested
268         usage |= mConsumerUsageBits;
269
270         int found = -1;
271         int dequeuedCount = 0;
272         bool tryAgain = true;
273         while (tryAgain) {
274             if (mAbandoned) {
275                 ST_LOGE("dequeueBuffer: BufferQueue has been abandoned!");
276                 return NO_INIT;
277             }
278
279             const int maxBufferCount = getMaxBufferCountLocked(async);
280             if (async && mOverrideMaxBufferCount) {
281                 // FIXME: some drivers are manually setting the buffer-count (which they
282                 // shouldn't), so we do this extra test here to handle that case.
283                 // This is TEMPORARY, until we get this fixed.
284                 if (mOverrideMaxBufferCount < maxBufferCount) {
285                     ST_LOGE("dequeueBuffer: async mode is invalid with buffercount override");
286                     return BAD_VALUE;
287                 }
288             }
289
290             // Free up any buffers that are in slots beyond the max buffer
291             // count.
292             for (int i = maxBufferCount; i < NUM_BUFFER_SLOTS; i++) {
293                 assert(mSlots[i].mBufferState == BufferSlot::FREE);
294                 if (mSlots[i].mGraphicBuffer != NULL) {
295                     freeBufferLocked(i);
296                     returnFlags |= IGraphicBufferProducer::RELEASE_ALL_BUFFERS;
297                 }
298             }
299
300             // look for a free buffer to give to the client
301             found = INVALID_BUFFER_SLOT;
302             dequeuedCount = 0;
303             for (int i = 0; i < maxBufferCount; i++) {
304                 const int state = mSlots[i].mBufferState;
305                 if (state == BufferSlot::DEQUEUED) {
306                     dequeuedCount++;
307                 }
308
309                 if (state == BufferSlot::FREE) {
310                     /* We return the oldest of the free buffers to avoid
311                      * stalling the producer if possible.  This is because
312                      * the consumer may still have pending reads of the
313                      * buffers in flight.
314                      */
315                     if ((found < 0) ||
316                             mSlots[i].mFrameNumber < mSlots[found].mFrameNumber) {
317                         found = i;
318                     }
319                 }
320             }
321
322             // clients are not allowed to dequeue more than one buffer
323             // if they didn't set a buffer count.
324             if (!mOverrideMaxBufferCount && dequeuedCount) {
325                 ST_LOGE("dequeueBuffer: can't dequeue multiple buffers without "
326                         "setting the buffer count");
327                 return -EINVAL;
328             }
329
330             // See whether a buffer has been queued since the last
331             // setBufferCount so we know whether to perform the min undequeued
332             // buffers check below.
333             if (mBufferHasBeenQueued) {
334                 // make sure the client is not trying to dequeue more buffers
335                 // than allowed.
336                 const int newUndequeuedCount = maxBufferCount - (dequeuedCount+1);
337                 const int minUndequeuedCount = getMinUndequeuedBufferCount(async);
338                 if (newUndequeuedCount < minUndequeuedCount) {
339                     ST_LOGE("dequeueBuffer: min undequeued buffer count (%d) "
340                             "exceeded (dequeued=%d undequeudCount=%d)",
341                             minUndequeuedCount, dequeuedCount,
342                             newUndequeuedCount);
343                     return -EBUSY;
344                 }
345             }
346
347             // If no buffer is found, wait for a buffer to be released or for
348             // the max buffer count to change.
349             tryAgain = found == INVALID_BUFFER_SLOT;
350             if (tryAgain) {
351                 if (mDequeueBufferCannotBlock) {
352                     ST_LOGE("dequeueBuffer: would block! returning an error instead.");
353                     return WOULD_BLOCK;
354                 }
355                 mDequeueCondition.wait(mMutex);
356             }
357         }
358
359
360         if (found == INVALID_BUFFER_SLOT) {
361             // This should not happen.
362             ST_LOGE("dequeueBuffer: no available buffer slots");
363             return -EBUSY;
364         }
365
366         const int buf = found;
367         *outBuf = found;
368
369         ATRACE_BUFFER_INDEX(buf);
370
371         const bool useDefaultSize = !w && !h;
372         if (useDefaultSize) {
373             // use the default size
374             w = mDefaultWidth;
375             h = mDefaultHeight;
376         }
377
378         mSlots[buf].mBufferState = BufferSlot::DEQUEUED;
379
380         const sp<GraphicBuffer>& buffer(mSlots[buf].mGraphicBuffer);
381         if ((buffer == NULL) ||
382             (uint32_t(buffer->width)  != w) ||
383             (uint32_t(buffer->height) != h) ||
384             (uint32_t(buffer->format) != format) ||
385             ((uint32_t(buffer->usage) & usage) != usage))
386         {
387             mSlots[buf].mAcquireCalled = false;
388             mSlots[buf].mGraphicBuffer = NULL;
389             mSlots[buf].mRequestBufferCalled = false;
390             mSlots[buf].mEglFence = EGL_NO_SYNC_KHR;
391             mSlots[buf].mFence = Fence::NO_FENCE;
392             mSlots[buf].mEglDisplay = EGL_NO_DISPLAY;
393
394             returnFlags |= IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION;
395         }
396
397         dpy = mSlots[buf].mEglDisplay;
398         eglFence = mSlots[buf].mEglFence;
399         *outFence = mSlots[buf].mFence;
400         mSlots[buf].mEglFence = EGL_NO_SYNC_KHR;
401         mSlots[buf].mFence = Fence::NO_FENCE;
402     }  // end lock scope
403
404     if (returnFlags & IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION) {
405         status_t error;
406         sp<GraphicBuffer> graphicBuffer(
407                 mGraphicBufferAlloc->createGraphicBuffer(
408                         w, h, format, usage, &error));
409         if (graphicBuffer == 0) {
410             ST_LOGE("dequeueBuffer: SurfaceComposer::createGraphicBuffer "
411                     "failed");
412             return error;
413         }
414
415         { // Scope for the lock
416             Mutex::Autolock lock(mMutex);
417
418             if (mAbandoned) {
419                 ST_LOGE("dequeueBuffer: BufferQueue has been abandoned!");
420                 return NO_INIT;
421             }
422
423             mSlots[*outBuf].mFrameNumber = ~0;
424             mSlots[*outBuf].mGraphicBuffer = graphicBuffer;
425         }
426     }
427
428     if (eglFence != EGL_NO_SYNC_KHR) {
429         EGLint result = eglClientWaitSyncKHR(dpy, eglFence, 0, 1000000000);
430         // If something goes wrong, log the error, but return the buffer without
431         // synchronizing access to it.  It's too late at this point to abort the
432         // dequeue operation.
433         if (result == EGL_FALSE) {
434             ST_LOGE("dequeueBuffer: error waiting for fence: %#x", eglGetError());
435         } else if (result == EGL_TIMEOUT_EXPIRED_KHR) {
436             ST_LOGE("dequeueBuffer: timeout waiting for fence");
437         }
438         eglDestroySyncKHR(dpy, eglFence);
439     }
440
441     ST_LOGV("dequeueBuffer: returning slot=%d/%llu buf=%p flags=%#x", *outBuf,
442             mSlots[*outBuf].mFrameNumber,
443             mSlots[*outBuf].mGraphicBuffer->handle, returnFlags);
444
445     return returnFlags;
446 }
447
448 status_t BufferQueue::queueBuffer(int buf,
449         const QueueBufferInput& input, QueueBufferOutput* output) {
450     ATRACE_CALL();
451     ATRACE_BUFFER_INDEX(buf);
452
453     Rect crop;
454     uint32_t transform;
455     int scalingMode;
456     int64_t timestamp;
457     bool async;
458     sp<Fence> fence;
459
460     input.deflate(&timestamp, &crop, &scalingMode, &transform, &async, &fence);
461
462     if (fence == NULL) {
463         ST_LOGE("queueBuffer: fence is NULL");
464         return BAD_VALUE;
465     }
466
467     switch (scalingMode) {
468         case NATIVE_WINDOW_SCALING_MODE_FREEZE:
469         case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW:
470         case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP:
471         case NATIVE_WINDOW_SCALING_MODE_NO_SCALE_CROP:
472             break;
473         default:
474             ST_LOGE("unknown scaling mode: %d", scalingMode);
475             return -EINVAL;
476     }
477
478     sp<ConsumerListener> listener;
479
480     { // scope for the lock
481         Mutex::Autolock lock(mMutex);
482
483         if (mAbandoned) {
484             ST_LOGE("queueBuffer: BufferQueue has been abandoned!");
485             return NO_INIT;
486         }
487
488         const int maxBufferCount = getMaxBufferCountLocked(async);
489         if (async && mOverrideMaxBufferCount) {
490             // FIXME: some drivers are manually setting the buffer-count (which they
491             // shouldn't), so we do this extra test here to handle that case.
492             // This is TEMPORARY, until we get this fixed.
493             if (mOverrideMaxBufferCount < maxBufferCount) {
494                 ST_LOGE("queueBuffer: async mode is invalid with buffercount override");
495                 return BAD_VALUE;
496             }
497         }
498         if (buf < 0 || buf >= maxBufferCount) {
499             ST_LOGE("queueBuffer: slot index out of range [0, %d]: %d",
500                     maxBufferCount, buf);
501             return -EINVAL;
502         } else if (mSlots[buf].mBufferState != BufferSlot::DEQUEUED) {
503             ST_LOGE("queueBuffer: slot %d is not owned by the client "
504                     "(state=%d)", buf, mSlots[buf].mBufferState);
505             return -EINVAL;
506         } else if (!mSlots[buf].mRequestBufferCalled) {
507             ST_LOGE("queueBuffer: slot %d was enqueued without requesting a "
508                     "buffer", buf);
509             return -EINVAL;
510         }
511
512         ST_LOGV("queueBuffer: slot=%d/%llu time=%#llx crop=[%d,%d,%d,%d] "
513                 "tr=%#x scale=%s",
514                 buf, mFrameCounter + 1, timestamp,
515                 crop.left, crop.top, crop.right, crop.bottom,
516                 transform, scalingModeName(scalingMode));
517
518         const sp<GraphicBuffer>& graphicBuffer(mSlots[buf].mGraphicBuffer);
519         Rect bufferRect(graphicBuffer->getWidth(), graphicBuffer->getHeight());
520         Rect croppedCrop;
521         crop.intersect(bufferRect, &croppedCrop);
522         if (croppedCrop != crop) {
523             ST_LOGE("queueBuffer: crop rect is not contained within the "
524                     "buffer in slot %d", buf);
525             return -EINVAL;
526         }
527
528         mSlots[buf].mFence = fence;
529         mSlots[buf].mBufferState = BufferSlot::QUEUED;
530         mFrameCounter++;
531         mSlots[buf].mFrameNumber = mFrameCounter;
532
533         BufferItem item;
534         item.mAcquireCalled = mSlots[buf].mAcquireCalled;
535         item.mGraphicBuffer = mSlots[buf].mGraphicBuffer;
536         item.mCrop = crop;
537         item.mTransform = transform;
538         item.mScalingMode = scalingMode;
539         item.mTimestamp = timestamp;
540         item.mFrameNumber = mFrameCounter;
541         item.mBuf = buf;
542         item.mFence = fence;
543         item.mIsDroppable = mDequeueBufferCannotBlock || async;
544
545         if (mQueue.empty()) {
546             // when the queue is empty, we can ignore "mDequeueBufferCannotBlock", and
547             // simply queue this buffer.
548             mQueue.push_back(item);
549             listener = mConsumerListener;
550         } else {
551             // when the queue is not empty, we need to look at the front buffer
552             // state and see if we need to replace it.
553             Fifo::iterator front(mQueue.begin());
554             if (front->mIsDroppable) {
555                 // buffer slot currently queued is marked free if still tracked
556                 if (stillTracking(front)) {
557                     mSlots[front->mBuf].mBufferState = BufferSlot::FREE;
558                 }
559                 // and we record the new buffer in the queued list
560                 *front = item;
561             } else {
562                 mQueue.push_back(item);
563                 listener = mConsumerListener;
564             }
565         }
566
567         mBufferHasBeenQueued = true;
568         mDequeueCondition.broadcast();
569
570         output->inflate(mDefaultWidth, mDefaultHeight, mTransformHint,
571                 mQueue.size());
572
573         ATRACE_INT(mConsumerName.string(), mQueue.size());
574     } // scope for the lock
575
576     // call back without lock held
577     if (listener != 0) {
578         listener->onFrameAvailable();
579     }
580     return NO_ERROR;
581 }
582
583 void BufferQueue::cancelBuffer(int buf, const sp<Fence>& fence) {
584     ATRACE_CALL();
585     ST_LOGV("cancelBuffer: slot=%d", buf);
586     Mutex::Autolock lock(mMutex);
587
588     if (mAbandoned) {
589         ST_LOGW("cancelBuffer: BufferQueue has been abandoned!");
590         return;
591     }
592
593     if (buf < 0 || buf >= NUM_BUFFER_SLOTS) {
594         ST_LOGE("cancelBuffer: slot index out of range [0, %d]: %d",
595                 NUM_BUFFER_SLOTS, buf);
596         return;
597     } else if (mSlots[buf].mBufferState != BufferSlot::DEQUEUED) {
598         ST_LOGE("cancelBuffer: slot %d is not owned by the client (state=%d)",
599                 buf, mSlots[buf].mBufferState);
600         return;
601     } else if (fence == NULL) {
602         ST_LOGE("cancelBuffer: fence is NULL");
603         return;
604     }
605     mSlots[buf].mBufferState = BufferSlot::FREE;
606     mSlots[buf].mFrameNumber = 0;
607     mSlots[buf].mFence = fence;
608     mDequeueCondition.broadcast();
609 }
610
611 status_t BufferQueue::connect(int api, bool producerControlledByApp, QueueBufferOutput* output) {
612     ATRACE_CALL();
613     ST_LOGV("connect: api=%d", api);
614     Mutex::Autolock lock(mMutex);
615
616     if (mAbandoned) {
617         ST_LOGE("connect: BufferQueue has been abandoned!");
618         return NO_INIT;
619     }
620
621     if (mConsumerListener == NULL) {
622         ST_LOGE("connect: BufferQueue has no consumer!");
623         return NO_INIT;
624     }
625
626     int err = NO_ERROR;
627     switch (api) {
628         case NATIVE_WINDOW_API_EGL:
629         case NATIVE_WINDOW_API_CPU:
630         case NATIVE_WINDOW_API_MEDIA:
631         case NATIVE_WINDOW_API_CAMERA:
632             if (mConnectedApi != NO_CONNECTED_API) {
633                 ST_LOGE("connect: already connected (cur=%d, req=%d)",
634                         mConnectedApi, api);
635                 err = -EINVAL;
636             } else {
637                 mConnectedApi = api;
638                 output->inflate(mDefaultWidth, mDefaultHeight, mTransformHint,
639                         mQueue.size());
640             }
641             break;
642         default:
643             err = -EINVAL;
644             break;
645     }
646
647     mBufferHasBeenQueued = false;
648     mDequeueBufferCannotBlock = mConsumerControlledByApp && producerControlledByApp;
649
650     return err;
651 }
652
653 status_t BufferQueue::disconnect(int api) {
654     ATRACE_CALL();
655     ST_LOGV("disconnect: api=%d", api);
656
657     int err = NO_ERROR;
658     sp<ConsumerListener> listener;
659
660     { // Scope for the lock
661         Mutex::Autolock lock(mMutex);
662
663         if (mAbandoned) {
664             // it is not really an error to disconnect after the surface
665             // has been abandoned, it should just be a no-op.
666             return NO_ERROR;
667         }
668
669         switch (api) {
670             case NATIVE_WINDOW_API_EGL:
671             case NATIVE_WINDOW_API_CPU:
672             case NATIVE_WINDOW_API_MEDIA:
673             case NATIVE_WINDOW_API_CAMERA:
674                 if (mConnectedApi == api) {
675                     freeAllBuffersLocked();
676                     mConnectedApi = NO_CONNECTED_API;
677                     mDequeueCondition.broadcast();
678                     listener = mConsumerListener;
679                 } else {
680                     ST_LOGE("disconnect: connected to another api (cur=%d, req=%d)",
681                             mConnectedApi, api);
682                     err = -EINVAL;
683                 }
684                 break;
685             default:
686                 ST_LOGE("disconnect: unknown API %d", api);
687                 err = -EINVAL;
688                 break;
689         }
690     }
691
692     if (listener != NULL) {
693         listener->onBuffersReleased();
694     }
695
696     return err;
697 }
698
699 void BufferQueue::dump(String8& result) const {
700     BufferQueue::dump(result, "");
701 }
702
703 void BufferQueue::dump(String8& result, const char* prefix) const {
704     Mutex::Autolock _l(mMutex);
705
706     String8 fifo;
707     int fifoSize = 0;
708     Fifo::const_iterator i(mQueue.begin());
709     while (i != mQueue.end()) {
710         fifo.appendFormat("%02d:%p crop=[%d,%d,%d,%d], "
711                 "xform=0x%02x, time=%#llx, scale=%s\n",
712                 i->mBuf, i->mGraphicBuffer.get(),
713                 i->mCrop.left, i->mCrop.top, i->mCrop.right,
714                 i->mCrop.bottom, i->mTransform, i->mTimestamp,
715                 scalingModeName(i->mScalingMode)
716                 );
717         i++;
718         fifoSize++;
719     }
720
721
722     result.appendFormat(
723             "%s-BufferQueue mMaxAcquiredBufferCount=%d, mDequeueBufferCannotBlock=%d, default-size=[%dx%d], "
724             "default-format=%d, transform-hint=%02x, FIFO(%d)={%s}\n",
725             prefix, mMaxAcquiredBufferCount, mDequeueBufferCannotBlock, mDefaultWidth,
726             mDefaultHeight, mDefaultBufferFormat, mTransformHint,
727             fifoSize, fifo.string());
728
729     struct {
730         const char * operator()(int state) const {
731             switch (state) {
732                 case BufferSlot::DEQUEUED: return "DEQUEUED";
733                 case BufferSlot::QUEUED: return "QUEUED";
734                 case BufferSlot::FREE: return "FREE";
735                 case BufferSlot::ACQUIRED: return "ACQUIRED";
736                 default: return "Unknown";
737             }
738         }
739     } stateName;
740
741     // just trim the free buffers to not spam the dump
742     int maxBufferCount = 0;
743     for (int i=NUM_BUFFER_SLOTS-1 ; i>=0 ; i--) {
744         const BufferSlot& slot(mSlots[i]);
745         if ((slot.mBufferState != BufferSlot::FREE) || (slot.mGraphicBuffer != NULL)) {
746             maxBufferCount = i+1;
747             break;
748         }
749     }
750
751     for (int i=0 ; i<maxBufferCount ; i++) {
752         const BufferSlot& slot(mSlots[i]);
753         const sp<GraphicBuffer>& buf(slot.mGraphicBuffer);
754         result.appendFormat(
755             "%s%s[%02d:%p] state=%-8s",
756                 prefix, (slot.mBufferState == BufferSlot::ACQUIRED)?">":" ", i, buf.get(),
757                 stateName(slot.mBufferState)
758         );
759
760         if (buf != NULL) {
761             result.appendFormat(
762                     ", %p [%4ux%4u:%4u,%3X]",
763                     buf->handle, buf->width, buf->height, buf->stride,
764                     buf->format);
765         }
766         result.append("\n");
767     }
768 }
769
770 void BufferQueue::freeBufferLocked(int slot) {
771     ST_LOGV("freeBufferLocked: slot=%d", slot);
772     mSlots[slot].mGraphicBuffer = 0;
773     if (mSlots[slot].mBufferState == BufferSlot::ACQUIRED) {
774         mSlots[slot].mNeedsCleanupOnRelease = true;
775     }
776     mSlots[slot].mBufferState = BufferSlot::FREE;
777     mSlots[slot].mFrameNumber = 0;
778     mSlots[slot].mAcquireCalled = false;
779
780     // destroy fence as BufferQueue now takes ownership
781     if (mSlots[slot].mEglFence != EGL_NO_SYNC_KHR) {
782         eglDestroySyncKHR(mSlots[slot].mEglDisplay, mSlots[slot].mEglFence);
783         mSlots[slot].mEglFence = EGL_NO_SYNC_KHR;
784     }
785     mSlots[slot].mFence = Fence::NO_FENCE;
786 }
787
788 void BufferQueue::freeAllBuffersLocked() {
789     mBufferHasBeenQueued = false;
790     for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
791         freeBufferLocked(i);
792     }
793 }
794
795 status_t BufferQueue::acquireBuffer(BufferItem *buffer, nsecs_t presentWhen) {
796     ATRACE_CALL();
797     Mutex::Autolock _l(mMutex);
798
799     // Check that the consumer doesn't currently have the maximum number of
800     // buffers acquired.  We allow the max buffer count to be exceeded by one
801     // buffer, so that the consumer can successfully set up the newly acquired
802     // buffer before releasing the old one.
803     int numAcquiredBuffers = 0;
804     for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
805         if (mSlots[i].mBufferState == BufferSlot::ACQUIRED) {
806             numAcquiredBuffers++;
807         }
808     }
809     if (numAcquiredBuffers >= mMaxAcquiredBufferCount+1) {
810         ST_LOGE("acquireBuffer: max acquired buffer count reached: %d (max=%d)",
811                 numAcquiredBuffers, mMaxAcquiredBufferCount);
812         return INVALID_OPERATION;
813     }
814
815     // check if queue is empty
816     // In asynchronous mode the list is guaranteed to be one buffer
817     // deep, while in synchronous mode we use the oldest buffer.
818     if (mQueue.empty()) {
819         return NO_BUFFER_AVAILABLE;
820     }
821
822     Fifo::iterator front(mQueue.begin());
823     int buf = front->mBuf;
824
825     // Compare the buffer's desired presentation time to the predicted
826     // actual display time.
827     //
828     // The "presentWhen" argument indicates when the buffer is expected
829     // to be presented on-screen.  If the buffer's desired-present time
830     // is earlier (less) than presentWhen, meaning it'll be displayed
831     // on time or possibly late, we acquire and return it.  If we don't want
832     // to display it until after the presentWhen time, we return PRESENT_LATER
833     // without acquiring it.
834     //
835     // To be safe, we don't refuse to acquire the buffer if presentWhen is
836     // more than one second in the future beyond the desired present time
837     // (i.e. we'd be holding the buffer for a really long time).
838     const int MAX_FUTURE_NSEC = 1000000000ULL;
839     nsecs_t desiredPresent = front->mTimestamp;
840     if (presentWhen != 0 && desiredPresent > presentWhen &&
841             desiredPresent - presentWhen < MAX_FUTURE_NSEC)
842     {
843         ALOGV("pts defer: des=%lld when=%lld (%lld) now=%lld",
844                 desiredPresent, presentWhen, desiredPresent - presentWhen,
845                 systemTime(CLOCK_MONOTONIC));
846         return PRESENT_LATER;
847     }
848     if (presentWhen != 0) {
849         ALOGV("pts accept: %p[%d] sig=%lld des=%lld when=%lld (%lld)",
850                 mSlots, buf, mSlots[buf].mFence->getSignalTime(),
851                 desiredPresent, presentWhen, desiredPresent - presentWhen);
852     }
853
854     *buffer = *front;
855     ATRACE_BUFFER_INDEX(buf);
856
857     ST_LOGV("acquireBuffer: acquiring { slot=%d/%llu, buffer=%p }",
858             front->mBuf, front->mFrameNumber,
859             front->mGraphicBuffer->handle);
860     // if front buffer still being tracked update slot state
861     if (stillTracking(front)) {
862         mSlots[buf].mAcquireCalled = true;
863         mSlots[buf].mNeedsCleanupOnRelease = false;
864         mSlots[buf].mBufferState = BufferSlot::ACQUIRED;
865         mSlots[buf].mFence = Fence::NO_FENCE;
866     }
867
868     // If the buffer has previously been acquired by the consumer, set
869     // mGraphicBuffer to NULL to avoid unnecessarily remapping this
870     // buffer on the consumer side.
871     if (buffer->mAcquireCalled) {
872         buffer->mGraphicBuffer = NULL;
873     }
874
875     mQueue.erase(front);
876     mDequeueCondition.broadcast();
877
878     ATRACE_INT(mConsumerName.string(), mQueue.size());
879
880     return NO_ERROR;
881 }
882
883 status_t BufferQueue::releaseBuffer(
884         int buf, uint64_t frameNumber, EGLDisplay display,
885         EGLSyncKHR eglFence, const sp<Fence>& fence) {
886     ATRACE_CALL();
887     ATRACE_BUFFER_INDEX(buf);
888
889     Mutex::Autolock _l(mMutex);
890
891     if (buf == INVALID_BUFFER_SLOT || fence == NULL) {
892         return BAD_VALUE;
893     }
894
895     // Check if this buffer slot is on the queue
896     bool slotQueued = false;
897     Fifo::iterator front(mQueue.begin());
898     while (front != mQueue.end() && !slotQueued) {
899         if (front->mBuf == buf)
900             slotQueued = true;
901         front++;
902     }
903
904     // If the frame number has changed because buffer has been reallocated,
905     // we can ignore this releaseBuffer for the old buffer.
906     if (frameNumber != mSlots[buf].mFrameNumber) {
907         // This should only occur if new buffer is still in the queue
908         ALOGE_IF(!slotQueued,
909                 "received old buffer(#%lld) after new buffer(#%lld) on same "
910                 "slot #%d already acquired", frameNumber,
911                 mSlots[buf].mFrameNumber, buf);
912         return STALE_BUFFER_SLOT;
913     }
914     // this should never happen
915     ALOGE_IF(slotQueued,
916             "received new buffer(#%lld) on slot #%d that has not yet been "
917             "acquired", frameNumber, buf);
918
919     // The buffer can now only be released if its in the acquired state
920     if (mSlots[buf].mBufferState == BufferSlot::ACQUIRED) {
921         mSlots[buf].mEglDisplay = display;
922         mSlots[buf].mEglFence = eglFence;
923         mSlots[buf].mFence = fence;
924         mSlots[buf].mBufferState = BufferSlot::FREE;
925     } else if (mSlots[buf].mNeedsCleanupOnRelease) {
926         ST_LOGV("releasing a stale buf %d its state was %d", buf, mSlots[buf].mBufferState);
927         mSlots[buf].mNeedsCleanupOnRelease = false;
928         return STALE_BUFFER_SLOT;
929     } else {
930         ST_LOGE("attempted to release buf %d but its state was %d", buf, mSlots[buf].mBufferState);
931         return -EINVAL;
932     }
933
934     mDequeueCondition.broadcast();
935     return NO_ERROR;
936 }
937
938 status_t BufferQueue::consumerConnect(const sp<ConsumerListener>& consumerListener,
939         bool controlledByApp) {
940     ST_LOGV("consumerConnect");
941     Mutex::Autolock lock(mMutex);
942
943     if (mAbandoned) {
944         ST_LOGE("consumerConnect: BufferQueue has been abandoned!");
945         return NO_INIT;
946     }
947     if (consumerListener == NULL) {
948         ST_LOGE("consumerConnect: consumerListener may not be NULL");
949         return BAD_VALUE;
950     }
951
952     mConsumerListener = consumerListener;
953     mConsumerControlledByApp = controlledByApp;
954
955     return NO_ERROR;
956 }
957
958 status_t BufferQueue::consumerDisconnect() {
959     ST_LOGV("consumerDisconnect");
960     Mutex::Autolock lock(mMutex);
961
962     if (mConsumerListener == NULL) {
963         ST_LOGE("consumerDisconnect: No consumer is connected!");
964         return -EINVAL;
965     }
966
967     mAbandoned = true;
968     mConsumerListener = NULL;
969     mQueue.clear();
970     freeAllBuffersLocked();
971     mDequeueCondition.broadcast();
972     return NO_ERROR;
973 }
974
975 status_t BufferQueue::getReleasedBuffers(uint32_t* slotMask) {
976     ST_LOGV("getReleasedBuffers");
977     Mutex::Autolock lock(mMutex);
978
979     if (mAbandoned) {
980         ST_LOGE("getReleasedBuffers: BufferQueue has been abandoned!");
981         return NO_INIT;
982     }
983
984     uint32_t mask = 0;
985     for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
986         if (!mSlots[i].mAcquireCalled) {
987             mask |= 1 << i;
988         }
989     }
990
991     // Remove buffers in flight (on the queue) from the mask where acquire has
992     // been called, as the consumer will not receive the buffer address, so
993     // it should not free these slots.
994     Fifo::iterator front(mQueue.begin());
995     while (front != mQueue.end()) {
996         if (front->mAcquireCalled)
997             mask &= ~(1 << front->mBuf);
998         front++;
999     }
1000
1001     *slotMask = mask;
1002
1003     ST_LOGV("getReleasedBuffers: returning mask %#x", mask);
1004     return NO_ERROR;
1005 }
1006
1007 status_t BufferQueue::setDefaultBufferSize(uint32_t w, uint32_t h)
1008 {
1009     ST_LOGV("setDefaultBufferSize: w=%d, h=%d", w, h);
1010     if (!w || !h) {
1011         ST_LOGE("setDefaultBufferSize: dimensions cannot be 0 (w=%d, h=%d)",
1012                 w, h);
1013         return BAD_VALUE;
1014     }
1015
1016     Mutex::Autolock lock(mMutex);
1017     mDefaultWidth = w;
1018     mDefaultHeight = h;
1019     return NO_ERROR;
1020 }
1021
1022 status_t BufferQueue::setDefaultMaxBufferCount(int bufferCount) {
1023     ATRACE_CALL();
1024     Mutex::Autolock lock(mMutex);
1025     return setDefaultMaxBufferCountLocked(bufferCount);
1026 }
1027
1028 status_t BufferQueue::setMaxAcquiredBufferCount(int maxAcquiredBuffers) {
1029     ATRACE_CALL();
1030     Mutex::Autolock lock(mMutex);
1031     if (maxAcquiredBuffers < 1 || maxAcquiredBuffers > MAX_MAX_ACQUIRED_BUFFERS) {
1032         ST_LOGE("setMaxAcquiredBufferCount: invalid count specified: %d",
1033                 maxAcquiredBuffers);
1034         return BAD_VALUE;
1035     }
1036     if (mConnectedApi != NO_CONNECTED_API) {
1037         return INVALID_OPERATION;
1038     }
1039     mMaxAcquiredBufferCount = maxAcquiredBuffers;
1040     return NO_ERROR;
1041 }
1042
1043 int BufferQueue::getMinUndequeuedBufferCount(bool async) const {
1044     return (mDequeueBufferCannotBlock || async) ?
1045                 mMaxAcquiredBufferCount+1 : mMaxAcquiredBufferCount;
1046 }
1047
1048 int BufferQueue::getMinMaxBufferCountLocked(bool async) const {
1049     return getMinUndequeuedBufferCount(async) + 1;
1050 }
1051
1052 int BufferQueue::getMaxBufferCountLocked(bool async) const {
1053     int minMaxBufferCount = getMinMaxBufferCountLocked(async);
1054
1055     int maxBufferCount = mDefaultMaxBufferCount;
1056     if (maxBufferCount < minMaxBufferCount) {
1057         maxBufferCount = minMaxBufferCount;
1058     }
1059     if (mOverrideMaxBufferCount != 0) {
1060         assert(mOverrideMaxBufferCount >= minMaxBufferCount);
1061         maxBufferCount = mOverrideMaxBufferCount;
1062     }
1063
1064     // Any buffers that are dequeued by the producer or sitting in the queue
1065     // waiting to be consumed need to have their slots preserved.  Such
1066     // buffers will temporarily keep the max buffer count up until the slots
1067     // no longer need to be preserved.
1068     for (int i = maxBufferCount; i < NUM_BUFFER_SLOTS; i++) {
1069         BufferSlot::BufferState state = mSlots[i].mBufferState;
1070         if (state == BufferSlot::QUEUED || state == BufferSlot::DEQUEUED) {
1071             maxBufferCount = i + 1;
1072         }
1073     }
1074
1075     return maxBufferCount;
1076 }
1077
1078 bool BufferQueue::stillTracking(const BufferItem *item) const {
1079     const BufferSlot &slot = mSlots[item->mBuf];
1080
1081     ST_LOGV("stillTracking?: item: { slot=%d/%llu, buffer=%p }, "
1082             "slot: { slot=%d/%llu, buffer=%p }",
1083             item->mBuf, item->mFrameNumber,
1084             (item->mGraphicBuffer.get() ? item->mGraphicBuffer->handle : 0),
1085             item->mBuf, slot.mFrameNumber,
1086             (slot.mGraphicBuffer.get() ? slot.mGraphicBuffer->handle : 0));
1087
1088     // Compare item with its original buffer slot.  We can check the slot
1089     // as the buffer would not be moved to a different slot by the producer.
1090     return (slot.mGraphicBuffer != NULL &&
1091             item->mGraphicBuffer->handle == slot.mGraphicBuffer->handle);
1092 }
1093
1094 BufferQueue::ProxyConsumerListener::ProxyConsumerListener(
1095         const wp<BufferQueue::ConsumerListener>& consumerListener):
1096         mConsumerListener(consumerListener) {}
1097
1098 BufferQueue::ProxyConsumerListener::~ProxyConsumerListener() {}
1099
1100 void BufferQueue::ProxyConsumerListener::onFrameAvailable() {
1101     sp<BufferQueue::ConsumerListener> listener(mConsumerListener.promote());
1102     if (listener != NULL) {
1103         listener->onFrameAvailable();
1104     }
1105 }
1106
1107 void BufferQueue::ProxyConsumerListener::onBuffersReleased() {
1108     sp<BufferQueue::ConsumerListener> listener(mConsumerListener.promote());
1109     if (listener != NULL) {
1110         listener->onBuffersReleased();
1111     }
1112 }
1113
1114 }; // namespace android