BufferQueueProducer.cpp 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109
  1. /*
  2. * Copyright 2014 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <inttypes.h>
  17. #define LOG_TAG "BufferQueueProducer"
  18. #define ATRACE_TAG ATRACE_TAG_GRAPHICS
  19. //#define LOG_NDEBUG 0
  20. #define EGL_EGLEXT_PROTOTYPES
  21. #include <gui/BufferItem.h>
  22. #include <gui/BufferQueueCore.h>
  23. #include <gui/BufferQueueProducer.h>
  24. #include <gui/IConsumerListener.h>
  25. #include <gui/IGraphicBufferAlloc.h>
  26. #include <gui/IProducerListener.h>
  27. #include <utils/Log.h>
  28. #include <utils/Trace.h>
  29. namespace android {
  30. BufferQueueProducer::BufferQueueProducer(const sp<BufferQueueCore>& core) :
  31. mCore(core),
  32. mSlots(core->mSlots),
  33. mConsumerName(),
  34. mStickyTransform(0),
  35. mLastQueueBufferFence(Fence::NO_FENCE),
  36. mCallbackMutex(),
  37. mNextCallbackTicket(0),
  38. mCurrentCallbackTicket(0),
  39. mCallbackCondition() {}
  40. BufferQueueProducer::~BufferQueueProducer() {}
  41. status_t BufferQueueProducer::requestBuffer(int slot, sp<GraphicBuffer>* buf) {
  42. ATRACE_CALL();
  43. BQ_LOGV("requestBuffer: slot %d", slot);
  44. Mutex::Autolock lock(mCore->mMutex);
  45. if (mCore->mIsAbandoned) {
  46. BQ_LOGE("requestBuffer: BufferQueue has been abandoned");
  47. return NO_INIT;
  48. }
  49. if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS) {
  50. BQ_LOGE("requestBuffer: slot index %d out of range [0, %d)",
  51. slot, BufferQueueDefs::NUM_BUFFER_SLOTS);
  52. return BAD_VALUE;
  53. } else if (mSlots[slot].mBufferState != BufferSlot::DEQUEUED) {
  54. BQ_LOGE("requestBuffer: slot %d is not owned by the producer "
  55. "(state = %d)", slot, mSlots[slot].mBufferState);
  56. return BAD_VALUE;
  57. }
  58. mSlots[slot].mRequestBufferCalled = true;
  59. *buf = mSlots[slot].mGraphicBuffer;
  60. return NO_ERROR;
  61. }
  62. status_t BufferQueueProducer::setBufferCount(int bufferCount) {
  63. ATRACE_CALL();
  64. BQ_LOGV("setBufferCount: count = %d", bufferCount);
  65. sp<IConsumerListener> listener;
  66. { // Autolock scope
  67. Mutex::Autolock lock(mCore->mMutex);
  68. mCore->waitWhileAllocatingLocked();
  69. if (mCore->mIsAbandoned) {
  70. BQ_LOGE("setBufferCount: BufferQueue has been abandoned");
  71. return NO_INIT;
  72. }
  73. if (bufferCount > BufferQueueDefs::NUM_BUFFER_SLOTS) {
  74. BQ_LOGE("setBufferCount: bufferCount %d too large (max %d)",
  75. bufferCount, BufferQueueDefs::NUM_BUFFER_SLOTS);
  76. return BAD_VALUE;
  77. }
  78. // There must be no dequeued buffers when changing the buffer count.
  79. for (int s = 0; s < BufferQueueDefs::NUM_BUFFER_SLOTS; ++s) {
  80. if (mSlots[s].mBufferState == BufferSlot::DEQUEUED) {
  81. BQ_LOGE("setBufferCount: buffer owned by producer");
  82. return BAD_VALUE;
  83. }
  84. }
  85. if (bufferCount == 0) {
  86. mCore->mOverrideMaxBufferCount = 0;
  87. mCore->mDequeueCondition.broadcast();
  88. return NO_ERROR;
  89. }
  90. const int minBufferSlots = mCore->getMinMaxBufferCountLocked(false);
  91. if (bufferCount < minBufferSlots) {
  92. BQ_LOGE("setBufferCount: requested buffer count %d is less than "
  93. "minimum %d", bufferCount, minBufferSlots);
  94. return BAD_VALUE;
  95. }
  96. // Here we are guaranteed that the producer doesn't have any dequeued
  97. // buffers and will release all of its buffer references. We don't
  98. // clear the queue, however, so that currently queued buffers still
  99. // get displayed.
  100. mCore->freeAllBuffersLocked();
  101. mCore->mOverrideMaxBufferCount = bufferCount;
  102. mCore->mDequeueCondition.broadcast();
  103. listener = mCore->mConsumerListener;
  104. } // Autolock scope
  105. // Call back without lock held
  106. if (listener != NULL) {
  107. listener->onBuffersReleased();
  108. }
  109. return NO_ERROR;
  110. }
  111. status_t BufferQueueProducer::waitForFreeSlotThenRelock(const char* caller,
  112. bool async, int* found, status_t* returnFlags) const {
  113. bool tryAgain = true;
  114. while (tryAgain) {
  115. if (mCore->mIsAbandoned) {
  116. BQ_LOGE("%s: BufferQueue has been abandoned", caller);
  117. return NO_INIT;
  118. }
  119. const int maxBufferCount = mCore->getMaxBufferCountLocked(async);
  120. if (async && mCore->mOverrideMaxBufferCount) {
  121. // FIXME: Some drivers are manually setting the buffer count
  122. // (which they shouldn't), so we do this extra test here to
  123. // handle that case. This is TEMPORARY until we get this fixed.
  124. if (mCore->mOverrideMaxBufferCount < maxBufferCount) {
  125. BQ_LOGE("%s: async mode is invalid with buffer count override",
  126. caller);
  127. return BAD_VALUE;
  128. }
  129. }
  130. // Free up any buffers that are in slots beyond the max buffer count
  131. for (int s = maxBufferCount; s < BufferQueueDefs::NUM_BUFFER_SLOTS; ++s) {
  132. assert(mSlots[s].mBufferState == BufferSlot::FREE);
  133. if (mSlots[s].mGraphicBuffer != NULL) {
  134. mCore->freeBufferLocked(s);
  135. *returnFlags |= RELEASE_ALL_BUFFERS;
  136. }
  137. }
  138. int dequeuedCount = 0;
  139. int acquiredCount = 0;
  140. for (int s = 0; s < maxBufferCount; ++s) {
  141. switch (mSlots[s].mBufferState) {
  142. case BufferSlot::DEQUEUED:
  143. ++dequeuedCount;
  144. break;
  145. case BufferSlot::ACQUIRED:
  146. ++acquiredCount;
  147. break;
  148. default:
  149. break;
  150. }
  151. }
  152. // Producers are not allowed to dequeue more than one buffer if they
  153. // did not set a buffer count
  154. if (!mCore->mOverrideMaxBufferCount && dequeuedCount) {
  155. BQ_LOGE("%s: can't dequeue multiple buffers without setting the "
  156. "buffer count", caller);
  157. return INVALID_OPERATION;
  158. }
  159. // See whether a buffer has been queued since the last
  160. // setBufferCount so we know whether to perform the min undequeued
  161. // buffers check below
  162. if (mCore->mBufferHasBeenQueued) {
  163. // Make sure the producer is not trying to dequeue more buffers
  164. // than allowed
  165. const int newUndequeuedCount =
  166. maxBufferCount - (dequeuedCount + 1);
  167. const int minUndequeuedCount =
  168. mCore->getMinUndequeuedBufferCountLocked(async);
  169. if (newUndequeuedCount < minUndequeuedCount) {
  170. BQ_LOGE("%s: min undequeued buffer count (%d) exceeded "
  171. "(dequeued=%d undequeued=%d)",
  172. caller, minUndequeuedCount,
  173. dequeuedCount, newUndequeuedCount);
  174. return INVALID_OPERATION;
  175. }
  176. }
  177. *found = BufferQueueCore::INVALID_BUFFER_SLOT;
  178. // If we disconnect and reconnect quickly, we can be in a state where
  179. // our slots are empty but we have many buffers in the queue. This can
  180. // cause us to run out of memory if we outrun the consumer. Wait here if
  181. // it looks like we have too many buffers queued up.
  182. bool tooManyBuffers = mCore->mQueue.size()
  183. > static_cast<size_t>(maxBufferCount);
  184. if (tooManyBuffers) {
  185. BQ_LOGV("%s: queue size is %zu, waiting", caller,
  186. mCore->mQueue.size());
  187. } else {
  188. if (!mCore->mFreeBuffers.empty()) {
  189. auto slot = mCore->mFreeBuffers.begin();
  190. *found = *slot;
  191. mCore->mFreeBuffers.erase(slot);
  192. } else if (mCore->mAllowAllocation && !mCore->mFreeSlots.empty()) {
  193. auto slot = mCore->mFreeSlots.begin();
  194. // Only return free slots up to the max buffer count
  195. if (*slot < maxBufferCount) {
  196. *found = *slot;
  197. mCore->mFreeSlots.erase(slot);
  198. }
  199. }
  200. }
  201. // If no buffer is found, or if the queue has too many buffers
  202. // outstanding, wait for a buffer to be acquired or released, or for the
  203. // max buffer count to change.
  204. tryAgain = (*found == BufferQueueCore::INVALID_BUFFER_SLOT) ||
  205. tooManyBuffers;
  206. if (tryAgain) {
  207. // Return an error if we're in non-blocking mode (producer and
  208. // consumer are controlled by the application).
  209. // However, the consumer is allowed to briefly acquire an extra
  210. // buffer (which could cause us to have to wait here), which is
  211. // okay, since it is only used to implement an atomic acquire +
  212. // release (e.g., in GLConsumer::updateTexImage())
  213. if (mCore->mDequeueBufferCannotBlock &&
  214. (acquiredCount <= mCore->mMaxAcquiredBufferCount)) {
  215. return WOULD_BLOCK;
  216. }
  217. mCore->mDequeueCondition.wait(mCore->mMutex);
  218. }
  219. } // while (tryAgain)
  220. return NO_ERROR;
  221. }
  222. status_t BufferQueueProducer::dequeueBuffer(int *outSlot,
  223. sp<android::Fence> *outFence, bool async,
  224. uint32_t width, uint32_t height, PixelFormat format, uint32_t usage) {
  225. ATRACE_CALL();
  226. { // Autolock scope
  227. Mutex::Autolock lock(mCore->mMutex);
  228. mConsumerName = mCore->mConsumerName;
  229. } // Autolock scope
  230. BQ_LOGV("dequeueBuffer: async=%s w=%u h=%u format=%#x, usage=%#x",
  231. async ? "true" : "false", width, height, format, usage);
  232. if ((width && !height) || (!width && height)) {
  233. BQ_LOGE("dequeueBuffer: invalid size: w=%u h=%u", width, height);
  234. return BAD_VALUE;
  235. }
  236. status_t returnFlags = NO_ERROR;
  237. EGLDisplay eglDisplay = EGL_NO_DISPLAY;
  238. EGLSyncKHR eglFence = EGL_NO_SYNC_KHR;
  239. bool attachedByConsumer = false;
  240. { // Autolock scope
  241. Mutex::Autolock lock(mCore->mMutex);
  242. mCore->waitWhileAllocatingLocked();
  243. if (format == 0) {
  244. format = mCore->mDefaultBufferFormat;
  245. }
  246. // Enable the usage bits the consumer requested
  247. usage |= mCore->mConsumerUsageBits;
  248. const bool useDefaultSize = !width && !height;
  249. if (useDefaultSize) {
  250. width = mCore->mDefaultWidth;
  251. height = mCore->mDefaultHeight;
  252. }
  253. int found = BufferItem::INVALID_BUFFER_SLOT;
  254. while (found == BufferItem::INVALID_BUFFER_SLOT) {
  255. status_t status = waitForFreeSlotThenRelock("dequeueBuffer", async,
  256. &found, &returnFlags);
  257. if (status != NO_ERROR) {
  258. return status;
  259. }
  260. // This should not happen
  261. if (found == BufferQueueCore::INVALID_BUFFER_SLOT) {
  262. BQ_LOGE("dequeueBuffer: no available buffer slots");
  263. return -EBUSY;
  264. }
  265. const sp<GraphicBuffer>& buffer(mSlots[found].mGraphicBuffer);
  266. // If we are not allowed to allocate new buffers,
  267. // waitForFreeSlotThenRelock must have returned a slot containing a
  268. // buffer. If this buffer would require reallocation to meet the
  269. // requested attributes, we free it and attempt to get another one.
  270. if (!mCore->mAllowAllocation) {
  271. if (buffer->needsReallocation(width, height, format, usage)) {
  272. mCore->freeBufferLocked(found);
  273. found = BufferItem::INVALID_BUFFER_SLOT;
  274. continue;
  275. }
  276. }
  277. }
  278. *outSlot = found;
  279. ATRACE_BUFFER_INDEX(found);
  280. attachedByConsumer = mSlots[found].mAttachedByConsumer;
  281. mSlots[found].mBufferState = BufferSlot::DEQUEUED;
  282. const sp<GraphicBuffer>& buffer(mSlots[found].mGraphicBuffer);
  283. if ((buffer == NULL) ||
  284. buffer->needsReallocation(width, height, format, usage))
  285. {
  286. mSlots[found].mAcquireCalled = false;
  287. mSlots[found].mGraphicBuffer = NULL;
  288. mSlots[found].mRequestBufferCalled = false;
  289. mSlots[found].mEglDisplay = EGL_NO_DISPLAY;
  290. mSlots[found].mEglFence = EGL_NO_SYNC_KHR;
  291. mSlots[found].mFence = Fence::NO_FENCE;
  292. mCore->mBufferAge = 0;
  293. returnFlags |= BUFFER_NEEDS_REALLOCATION;
  294. } else {
  295. // We add 1 because that will be the frame number when this buffer
  296. // is queued
  297. mCore->mBufferAge =
  298. mCore->mFrameCounter + 1 - mSlots[found].mFrameNumber;
  299. }
  300. BQ_LOGV("dequeueBuffer: setting buffer age to %" PRIu64,
  301. mCore->mBufferAge);
  302. if (CC_UNLIKELY(mSlots[found].mFence == NULL)) {
  303. BQ_LOGE("dequeueBuffer: about to return a NULL fence - "
  304. "slot=%d w=%d h=%d format=%u",
  305. found, buffer->width, buffer->height, buffer->format);
  306. }
  307. eglDisplay = mSlots[found].mEglDisplay;
  308. eglFence = mSlots[found].mEglFence;
  309. *outFence = mSlots[found].mFence;
  310. mSlots[found].mEglFence = EGL_NO_SYNC_KHR;
  311. mSlots[found].mFence = Fence::NO_FENCE;
  312. mCore->validateConsistencyLocked();
  313. } // Autolock scope
  314. if (returnFlags & BUFFER_NEEDS_REALLOCATION) {
  315. status_t error;
  316. BQ_LOGV("dequeueBuffer: allocating a new buffer for slot %d", *outSlot);
  317. sp<GraphicBuffer> graphicBuffer(mCore->mAllocator->createGraphicBuffer(
  318. width, height, format, usage, &error));
  319. if (graphicBuffer == NULL) {
  320. BQ_LOGE("dequeueBuffer: createGraphicBuffer failed");
  321. return error;
  322. }
  323. { // Autolock scope
  324. Mutex::Autolock lock(mCore->mMutex);
  325. if (mCore->mIsAbandoned) {
  326. BQ_LOGE("dequeueBuffer: BufferQueue has been abandoned");
  327. return NO_INIT;
  328. }
  329. graphicBuffer->setGenerationNumber(mCore->mGenerationNumber);
  330. mSlots[*outSlot].mGraphicBuffer = graphicBuffer;
  331. } // Autolock scope
  332. }
  333. if (attachedByConsumer) {
  334. returnFlags |= BUFFER_NEEDS_REALLOCATION;
  335. }
  336. if (eglFence != EGL_NO_SYNC_KHR) {
  337. EGLint result = eglClientWaitSyncKHR(eglDisplay, eglFence, 0,
  338. 1000000000);
  339. // If something goes wrong, log the error, but return the buffer without
  340. // synchronizing access to it. It's too late at this point to abort the
  341. // dequeue operation.
  342. if (result == EGL_FALSE) {
  343. BQ_LOGE("dequeueBuffer: error %#x waiting for fence",
  344. eglGetError());
  345. } else if (result == EGL_TIMEOUT_EXPIRED_KHR) {
  346. BQ_LOGE("dequeueBuffer: timeout waiting for fence");
  347. }
  348. eglDestroySyncKHR(eglDisplay, eglFence);
  349. }
  350. BQ_LOGV("dequeueBuffer: returning slot=%d/%" PRIu64 " buf=%p flags=%#x",
  351. *outSlot,
  352. mSlots[*outSlot].mFrameNumber,
  353. mSlots[*outSlot].mGraphicBuffer->handle, returnFlags);
  354. return returnFlags;
  355. }
  356. status_t BufferQueueProducer::detachBuffer(int slot) {
  357. ATRACE_CALL();
  358. ATRACE_BUFFER_INDEX(slot);
  359. BQ_LOGV("detachBuffer(P): slot %d", slot);
  360. Mutex::Autolock lock(mCore->mMutex);
  361. if (mCore->mIsAbandoned) {
  362. BQ_LOGE("detachBuffer(P): BufferQueue has been abandoned");
  363. return NO_INIT;
  364. }
  365. if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS) {
  366. BQ_LOGE("detachBuffer(P): slot index %d out of range [0, %d)",
  367. slot, BufferQueueDefs::NUM_BUFFER_SLOTS);
  368. return BAD_VALUE;
  369. } else if (mSlots[slot].mBufferState != BufferSlot::DEQUEUED) {
  370. BQ_LOGE("detachBuffer(P): slot %d is not owned by the producer "
  371. "(state = %d)", slot, mSlots[slot].mBufferState);
  372. return BAD_VALUE;
  373. } else if (!mSlots[slot].mRequestBufferCalled) {
  374. BQ_LOGE("detachBuffer(P): buffer in slot %d has not been requested",
  375. slot);
  376. return BAD_VALUE;
  377. }
  378. mCore->freeBufferLocked(slot);
  379. mCore->mDequeueCondition.broadcast();
  380. mCore->validateConsistencyLocked();
  381. return NO_ERROR;
  382. }
  383. status_t BufferQueueProducer::detachNextBuffer(sp<GraphicBuffer>* outBuffer,
  384. sp<Fence>* outFence) {
  385. ATRACE_CALL();
  386. if (outBuffer == NULL) {
  387. BQ_LOGE("detachNextBuffer: outBuffer must not be NULL");
  388. return BAD_VALUE;
  389. } else if (outFence == NULL) {
  390. BQ_LOGE("detachNextBuffer: outFence must not be NULL");
  391. return BAD_VALUE;
  392. }
  393. Mutex::Autolock lock(mCore->mMutex);
  394. mCore->waitWhileAllocatingLocked();
  395. if (mCore->mIsAbandoned) {
  396. BQ_LOGE("detachNextBuffer: BufferQueue has been abandoned");
  397. return NO_INIT;
  398. }
  399. if (mCore->mFreeBuffers.empty()) {
  400. return NO_MEMORY;
  401. }
  402. int found = mCore->mFreeBuffers.front();
  403. mCore->mFreeBuffers.remove(found);
  404. BQ_LOGV("detachNextBuffer detached slot %d", found);
  405. *outBuffer = mSlots[found].mGraphicBuffer;
  406. *outFence = mSlots[found].mFence;
  407. mCore->freeBufferLocked(found);
  408. mCore->validateConsistencyLocked();
  409. return NO_ERROR;
  410. }
  411. status_t BufferQueueProducer::attachBuffer(int* outSlot,
  412. const sp<android::GraphicBuffer>& buffer) {
  413. ATRACE_CALL();
  414. if (outSlot == NULL) {
  415. BQ_LOGE("attachBuffer(P): outSlot must not be NULL");
  416. return BAD_VALUE;
  417. } else if (buffer == NULL) {
  418. BQ_LOGE("attachBuffer(P): cannot attach NULL buffer");
  419. return BAD_VALUE;
  420. }
  421. Mutex::Autolock lock(mCore->mMutex);
  422. mCore->waitWhileAllocatingLocked();
  423. if (buffer->getGenerationNumber() != mCore->mGenerationNumber) {
  424. BQ_LOGE("attachBuffer: generation number mismatch [buffer %u] "
  425. "[queue %u]", buffer->getGenerationNumber(),
  426. mCore->mGenerationNumber);
  427. return BAD_VALUE;
  428. }
  429. status_t returnFlags = NO_ERROR;
  430. int found;
  431. // TODO: Should we provide an async flag to attachBuffer? It seems
  432. // unlikely that buffers which we are attaching to a BufferQueue will
  433. // be asynchronous (droppable), but it may not be impossible.
  434. status_t status = waitForFreeSlotThenRelock("attachBuffer(P)", false,
  435. &found, &returnFlags);
  436. if (status != NO_ERROR) {
  437. return status;
  438. }
  439. // This should not happen
  440. if (found == BufferQueueCore::INVALID_BUFFER_SLOT) {
  441. BQ_LOGE("attachBuffer(P): no available buffer slots");
  442. return -EBUSY;
  443. }
  444. *outSlot = found;
  445. ATRACE_BUFFER_INDEX(*outSlot);
  446. BQ_LOGV("attachBuffer(P): returning slot %d flags=%#x",
  447. *outSlot, returnFlags);
  448. mSlots[*outSlot].mGraphicBuffer = buffer;
  449. mSlots[*outSlot].mBufferState = BufferSlot::DEQUEUED;
  450. mSlots[*outSlot].mEglFence = EGL_NO_SYNC_KHR;
  451. mSlots[*outSlot].mFence = Fence::NO_FENCE;
  452. mSlots[*outSlot].mRequestBufferCalled = true;
  453. mCore->validateConsistencyLocked();
  454. return returnFlags;
  455. }
  456. status_t BufferQueueProducer::queueBuffer(int slot,
  457. const QueueBufferInput &input, QueueBufferOutput *output) {
  458. ATRACE_CALL();
  459. ATRACE_BUFFER_INDEX(slot);
  460. int64_t timestamp;
  461. bool isAutoTimestamp;
  462. android_dataspace dataSpace;
  463. Rect crop;
  464. int scalingMode;
  465. uint32_t transform;
  466. uint32_t stickyTransform;
  467. bool async;
  468. sp<Fence> fence;
  469. input.deflate(&timestamp, &isAutoTimestamp, &dataSpace, &crop, &scalingMode,
  470. &transform, &async, &fence, &stickyTransform);
  471. Region surfaceDamage = input.getSurfaceDamage();
  472. if (fence == NULL) {
  473. BQ_LOGE("queueBuffer: fence is NULL");
  474. return BAD_VALUE;
  475. }
  476. switch (scalingMode) {
  477. case NATIVE_WINDOW_SCALING_MODE_FREEZE:
  478. case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW:
  479. case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP:
  480. case NATIVE_WINDOW_SCALING_MODE_NO_SCALE_CROP:
  481. break;
  482. default:
  483. BQ_LOGE("queueBuffer: unknown scaling mode %d", scalingMode);
  484. return BAD_VALUE;
  485. }
  486. sp<IConsumerListener> frameAvailableListener;
  487. sp<IConsumerListener> frameReplacedListener;
  488. int callbackTicket = 0;
  489. BufferItem item;
  490. { // Autolock scope
  491. Mutex::Autolock lock(mCore->mMutex);
  492. if (mCore->mIsAbandoned) {
  493. BQ_LOGE("queueBuffer: BufferQueue has been abandoned");
  494. return NO_INIT;
  495. }
  496. const int maxBufferCount = mCore->getMaxBufferCountLocked(async);
  497. if (async && mCore->mOverrideMaxBufferCount) {
  498. // FIXME: Some drivers are manually setting the buffer count
  499. // (which they shouldn't), so we do this extra test here to
  500. // handle that case. This is TEMPORARY until we get this fixed.
  501. if (mCore->mOverrideMaxBufferCount < maxBufferCount) {
  502. BQ_LOGE("queueBuffer: async mode is invalid with "
  503. "buffer count override");
  504. return BAD_VALUE;
  505. }
  506. }
  507. if (slot < 0 || slot >= maxBufferCount) {
  508. BQ_LOGE("queueBuffer: slot index %d out of range [0, %d)",
  509. slot, maxBufferCount);
  510. return BAD_VALUE;
  511. } else if (mSlots[slot].mBufferState != BufferSlot::DEQUEUED) {
  512. BQ_LOGE("queueBuffer: slot %d is not owned by the producer "
  513. "(state = %d)", slot, mSlots[slot].mBufferState);
  514. return BAD_VALUE;
  515. } else if (!mSlots[slot].mRequestBufferCalled) {
  516. BQ_LOGE("queueBuffer: slot %d was queued without requesting "
  517. "a buffer", slot);
  518. return BAD_VALUE;
  519. }
  520. BQ_LOGV("queueBuffer: slot=%d/%" PRIu64 " time=%" PRIu64 " dataSpace=%d"
  521. " crop=[%d,%d,%d,%d] transform=%#x scale=%s",
  522. slot, mCore->mFrameCounter + 1, timestamp, dataSpace,
  523. crop.left, crop.top, crop.right, crop.bottom, transform,
  524. BufferItem::scalingModeName(static_cast<uint32_t>(scalingMode)));
  525. const sp<GraphicBuffer>& graphicBuffer(mSlots[slot].mGraphicBuffer);
  526. Rect bufferRect(graphicBuffer->getWidth(), graphicBuffer->getHeight());
  527. Rect croppedRect;
  528. crop.intersect(bufferRect, &croppedRect);
  529. if (croppedRect != crop) {
  530. BQ_LOGE("queueBuffer: crop rect is not contained within the "
  531. "buffer in slot %d", slot);
  532. return BAD_VALUE;
  533. }
  534. // Override UNKNOWN dataspace with consumer default
  535. if (dataSpace == HAL_DATASPACE_UNKNOWN) {
  536. dataSpace = mCore->mDefaultBufferDataSpace;
  537. }
  538. mSlots[slot].mFence = fence;
  539. mSlots[slot].mBufferState = BufferSlot::QUEUED;
  540. ++mCore->mFrameCounter;
  541. mSlots[slot].mFrameNumber = mCore->mFrameCounter;
  542. item.mAcquireCalled = mSlots[slot].mAcquireCalled;
  543. item.mGraphicBuffer = mSlots[slot].mGraphicBuffer;
  544. item.mCrop = crop;
  545. item.mTransform = transform &
  546. ~static_cast<uint32_t>(NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY);
  547. item.mTransformToDisplayInverse =
  548. (transform & NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY) != 0;
  549. item.mScalingMode = static_cast<uint32_t>(scalingMode);
  550. item.mTimestamp = timestamp;
  551. item.mIsAutoTimestamp = isAutoTimestamp;
  552. item.mDataSpace = dataSpace;
  553. item.mFrameNumber = mCore->mFrameCounter;
  554. item.mSlot = slot;
  555. item.mFence = fence;
  556. item.mIsDroppable = mCore->mDequeueBufferCannotBlock || async;
  557. item.mSurfaceDamage = surfaceDamage;
  558. mStickyTransform = stickyTransform;
  559. if (mCore->mQueue.empty()) {
  560. // When the queue is empty, we can ignore mDequeueBufferCannotBlock
  561. // and simply queue this buffer
  562. mCore->mQueue.push_back(item);
  563. frameAvailableListener = mCore->mConsumerListener;
  564. } else {
  565. // When the queue is not empty, we need to look at the front buffer
  566. // state to see if we need to replace it
  567. BufferQueueCore::Fifo::iterator front(mCore->mQueue.begin());
  568. if (front->mIsDroppable) {
  569. // If the front queued buffer is still being tracked, we first
  570. // mark it as freed
  571. if (mCore->stillTracking(front)) {
  572. mSlots[front->mSlot].mBufferState = BufferSlot::FREE;
  573. mCore->mFreeBuffers.push_front(front->mSlot);
  574. }
  575. // Overwrite the droppable buffer with the incoming one
  576. *front = item;
  577. frameReplacedListener = mCore->mConsumerListener;
  578. } else {
  579. mCore->mQueue.push_back(item);
  580. frameAvailableListener = mCore->mConsumerListener;
  581. }
  582. }
  583. mCore->mBufferHasBeenQueued = true;
  584. mCore->mDequeueCondition.broadcast();
  585. output->inflate(mCore->mDefaultWidth, mCore->mDefaultHeight,
  586. mCore->mTransformHint,
  587. static_cast<uint32_t>(mCore->mQueue.size()));
  588. ATRACE_INT(mCore->mConsumerName.string(), mCore->mQueue.size());
  589. // Take a ticket for the callback functions
  590. callbackTicket = mNextCallbackTicket++;
  591. mCore->validateConsistencyLocked();
  592. } // Autolock scope
  593. // Don't send the GraphicBuffer through the callback, and don't send
  594. // the slot number, since the consumer shouldn't need it
  595. item.mGraphicBuffer.clear();
  596. item.mSlot = BufferItem::INVALID_BUFFER_SLOT;
  597. // Call back without the main BufferQueue lock held, but with the callback
  598. // lock held so we can ensure that callbacks occur in order
  599. {
  600. Mutex::Autolock lock(mCallbackMutex);
  601. while (callbackTicket != mCurrentCallbackTicket) {
  602. mCallbackCondition.wait(mCallbackMutex);
  603. }
  604. if (frameAvailableListener != NULL) {
  605. frameAvailableListener->onFrameAvailable(item);
  606. } else if (frameReplacedListener != NULL) {
  607. frameReplacedListener->onFrameReplaced(item);
  608. }
  609. ++mCurrentCallbackTicket;
  610. mCallbackCondition.broadcast();
  611. }
  612. // Wait without lock held
  613. if (mCore->mConnectedApi == NATIVE_WINDOW_API_EGL) {
  614. // Waiting here allows for two full buffers to be queued but not a
  615. // third. In the event that frames take varying time, this makes a
  616. // small trade-off in favor of latency rather than throughput.
  617. mLastQueueBufferFence->waitForever("Throttling EGL Production");
  618. mLastQueueBufferFence = fence;
  619. }
  620. return NO_ERROR;
  621. }
  622. void BufferQueueProducer::cancelBuffer(int slot, const sp<Fence>& fence) {
  623. ATRACE_CALL();
  624. BQ_LOGV("cancelBuffer: slot %d", slot);
  625. Mutex::Autolock lock(mCore->mMutex);
  626. if (mCore->mIsAbandoned) {
  627. BQ_LOGE("cancelBuffer: BufferQueue has been abandoned");
  628. return;
  629. }
  630. if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS) {
  631. BQ_LOGE("cancelBuffer: slot index %d out of range [0, %d)",
  632. slot, BufferQueueDefs::NUM_BUFFER_SLOTS);
  633. return;
  634. } else if (mSlots[slot].mBufferState != BufferSlot::DEQUEUED) {
  635. BQ_LOGE("cancelBuffer: slot %d is not owned by the producer "
  636. "(state = %d)", slot, mSlots[slot].mBufferState);
  637. return;
  638. } else if (fence == NULL) {
  639. BQ_LOGE("cancelBuffer: fence is NULL");
  640. return;
  641. }
  642. mCore->mFreeBuffers.push_front(slot);
  643. mSlots[slot].mBufferState = BufferSlot::FREE;
  644. mSlots[slot].mFence = fence;
  645. mCore->mDequeueCondition.broadcast();
  646. mCore->validateConsistencyLocked();
  647. }
  648. int BufferQueueProducer::query(int what, int *outValue) {
  649. ATRACE_CALL();
  650. Mutex::Autolock lock(mCore->mMutex);
  651. if (outValue == NULL) {
  652. BQ_LOGE("query: outValue was NULL");
  653. return BAD_VALUE;
  654. }
  655. if (mCore->mIsAbandoned) {
  656. BQ_LOGE("query: BufferQueue has been abandoned");
  657. return NO_INIT;
  658. }
  659. int value;
  660. switch (what) {
  661. case NATIVE_WINDOW_WIDTH:
  662. value = static_cast<int32_t>(mCore->mDefaultWidth);
  663. break;
  664. case NATIVE_WINDOW_HEIGHT:
  665. value = static_cast<int32_t>(mCore->mDefaultHeight);
  666. break;
  667. case NATIVE_WINDOW_FORMAT:
  668. value = static_cast<int32_t>(mCore->mDefaultBufferFormat);
  669. break;
  670. case NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS:
  671. value = mCore->getMinUndequeuedBufferCountLocked(false);
  672. break;
  673. case NATIVE_WINDOW_STICKY_TRANSFORM:
  674. value = static_cast<int32_t>(mStickyTransform);
  675. break;
  676. case NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND:
  677. value = (mCore->mQueue.size() > 1);
  678. break;
  679. case NATIVE_WINDOW_CONSUMER_USAGE_BITS:
  680. value = static_cast<int32_t>(mCore->mConsumerUsageBits);
  681. break;
  682. case NATIVE_WINDOW_DEFAULT_DATASPACE:
  683. value = static_cast<int32_t>(mCore->mDefaultBufferDataSpace);
  684. break;
  685. case NATIVE_WINDOW_BUFFER_AGE:
  686. if (mCore->mBufferAge > INT32_MAX) {
  687. value = 0;
  688. } else {
  689. value = static_cast<int32_t>(mCore->mBufferAge);
  690. }
  691. break;
  692. default:
  693. return BAD_VALUE;
  694. }
  695. BQ_LOGV("query: %d? %d", what, value);
  696. *outValue = value;
  697. return NO_ERROR;
  698. }
  699. status_t BufferQueueProducer::connect(const sp<IProducerListener>& listener,
  700. int api, bool producerControlledByApp, QueueBufferOutput *output) {
  701. ATRACE_CALL();
  702. Mutex::Autolock lock(mCore->mMutex);
  703. mConsumerName = mCore->mConsumerName;
  704. BQ_LOGV("connect(P): api=%d producerControlledByApp=%s", api,
  705. producerControlledByApp ? "true" : "false");
  706. if (mCore->mIsAbandoned) {
  707. BQ_LOGE("connect(P): BufferQueue has been abandoned");
  708. return NO_INIT;
  709. }
  710. if (mCore->mConsumerListener == NULL) {
  711. BQ_LOGE("connect(P): BufferQueue has no consumer");
  712. return NO_INIT;
  713. }
  714. if (output == NULL) {
  715. BQ_LOGE("connect(P): output was NULL");
  716. return BAD_VALUE;
  717. }
  718. if (mCore->mConnectedApi != BufferQueueCore::NO_CONNECTED_API) {
  719. BQ_LOGE("connect(P): already connected (cur=%d req=%d)",
  720. mCore->mConnectedApi, api);
  721. return BAD_VALUE;
  722. }
  723. int status = NO_ERROR;
  724. switch (api) {
  725. case NATIVE_WINDOW_API_EGL:
  726. case NATIVE_WINDOW_API_CPU:
  727. case NATIVE_WINDOW_API_MEDIA:
  728. case NATIVE_WINDOW_API_CAMERA:
  729. mCore->mConnectedApi = api;
  730. output->inflate(mCore->mDefaultWidth, mCore->mDefaultHeight,
  731. mCore->mTransformHint,
  732. static_cast<uint32_t>(mCore->mQueue.size()));
  733. // Set up a death notification so that we can disconnect
  734. // automatically if the remote producer dies
  735. if (listener != NULL &&
  736. IInterface::asBinder(listener)->remoteBinder() != NULL) {
  737. status = IInterface::asBinder(listener)->linkToDeath(
  738. static_cast<IBinder::DeathRecipient*>(this));
  739. if (status != NO_ERROR) {
  740. BQ_LOGE("connect(P): linkToDeath failed: %s (%d)",
  741. strerror(-status), status);
  742. }
  743. }
  744. mCore->mConnectedProducerListener = listener;
  745. break;
  746. default:
  747. BQ_LOGE("connect(P): unknown API %d", api);
  748. status = BAD_VALUE;
  749. break;
  750. }
  751. mCore->mBufferHasBeenQueued = false;
  752. mCore->mDequeueBufferCannotBlock =
  753. mCore->mConsumerControlledByApp && producerControlledByApp;
  754. mCore->mAllowAllocation = true;
  755. return status;
  756. }
  757. status_t BufferQueueProducer::disconnect(int api) {
  758. ATRACE_CALL();
  759. BQ_LOGV("disconnect(P): api %d", api);
  760. int status = NO_ERROR;
  761. sp<IConsumerListener> listener;
  762. { // Autolock scope
  763. Mutex::Autolock lock(mCore->mMutex);
  764. mCore->waitWhileAllocatingLocked();
  765. if (mCore->mIsAbandoned) {
  766. // It's not really an error to disconnect after the surface has
  767. // been abandoned; it should just be a no-op.
  768. return NO_ERROR;
  769. }
  770. switch (api) {
  771. case NATIVE_WINDOW_API_EGL:
  772. case NATIVE_WINDOW_API_CPU:
  773. case NATIVE_WINDOW_API_MEDIA:
  774. case NATIVE_WINDOW_API_CAMERA:
  775. if (mCore->mConnectedApi == api) {
  776. mCore->freeAllBuffersLocked();
  777. // Remove our death notification callback if we have one
  778. if (mCore->mConnectedProducerListener != NULL) {
  779. sp<IBinder> token =
  780. IInterface::asBinder(mCore->mConnectedProducerListener);
  781. // This can fail if we're here because of the death
  782. // notification, but we just ignore it
  783. token->unlinkToDeath(
  784. static_cast<IBinder::DeathRecipient*>(this));
  785. }
  786. mCore->mConnectedProducerListener = NULL;
  787. mCore->mConnectedApi = BufferQueueCore::NO_CONNECTED_API;
  788. mCore->mSidebandStream.clear();
  789. mCore->mDequeueCondition.broadcast();
  790. listener = mCore->mConsumerListener;
  791. } else if (mCore->mConnectedApi != BufferQueueCore::NO_CONNECTED_API) {
  792. BQ_LOGE("disconnect(P): still connected to another API "
  793. "(cur=%d req=%d)", mCore->mConnectedApi, api);
  794. status = BAD_VALUE;
  795. }
  796. break;
  797. default:
  798. BQ_LOGE("disconnect(P): unknown API %d", api);
  799. status = BAD_VALUE;
  800. break;
  801. }
  802. } // Autolock scope
  803. // Call back without lock held
  804. if (listener != NULL) {
  805. listener->onBuffersReleased();
  806. }
  807. return status;
  808. }
  809. status_t BufferQueueProducer::setSidebandStream(const sp<NativeHandle>& stream) {
  810. sp<IConsumerListener> listener;
  811. { // Autolock scope
  812. Mutex::Autolock _l(mCore->mMutex);
  813. mCore->mSidebandStream = stream;
  814. listener = mCore->mConsumerListener;
  815. } // Autolock scope
  816. if (listener != NULL) {
  817. listener->onSidebandStreamChanged();
  818. }
  819. return NO_ERROR;
  820. }
  821. void BufferQueueProducer::allocateBuffers(bool async, uint32_t width,
  822. uint32_t height, PixelFormat format, uint32_t usage) {
  823. ATRACE_CALL();
  824. while (true) {
  825. Vector<int> freeSlots;
  826. size_t newBufferCount = 0;
  827. uint32_t allocWidth = 0;
  828. uint32_t allocHeight = 0;
  829. PixelFormat allocFormat = PIXEL_FORMAT_UNKNOWN;
  830. uint32_t allocUsage = 0;
  831. { // Autolock scope
  832. Mutex::Autolock lock(mCore->mMutex);
  833. mCore->waitWhileAllocatingLocked();
  834. if (!mCore->mAllowAllocation) {
  835. BQ_LOGE("allocateBuffers: allocation is not allowed for this "
  836. "BufferQueue");
  837. return;
  838. }
  839. int currentBufferCount = 0;
  840. for (int slot = 0; slot < BufferQueueDefs::NUM_BUFFER_SLOTS; ++slot) {
  841. if (mSlots[slot].mGraphicBuffer != NULL) {
  842. ++currentBufferCount;
  843. } else {
  844. if (mSlots[slot].mBufferState != BufferSlot::FREE) {
  845. BQ_LOGE("allocateBuffers: slot %d without buffer is not FREE",
  846. slot);
  847. continue;
  848. }
  849. freeSlots.push_back(slot);
  850. }
  851. }
  852. int maxBufferCount = mCore->getMaxBufferCountLocked(async);
  853. BQ_LOGV("allocateBuffers: allocating from %d buffers up to %d buffers",
  854. currentBufferCount, maxBufferCount);
  855. if (maxBufferCount <= currentBufferCount)
  856. return;
  857. newBufferCount =
  858. static_cast<size_t>(maxBufferCount - currentBufferCount);
  859. if (freeSlots.size() < newBufferCount) {
  860. BQ_LOGE("allocateBuffers: ran out of free slots");
  861. return;
  862. }
  863. allocWidth = width > 0 ? width : mCore->mDefaultWidth;
  864. allocHeight = height > 0 ? height : mCore->mDefaultHeight;
  865. allocFormat = format != 0 ? format : mCore->mDefaultBufferFormat;
  866. allocUsage = usage | mCore->mConsumerUsageBits;
  867. mCore->mIsAllocating = true;
  868. } // Autolock scope
  869. Vector<sp<GraphicBuffer>> buffers;
  870. for (size_t i = 0; i < newBufferCount; ++i) {
  871. status_t result = NO_ERROR;
  872. sp<GraphicBuffer> graphicBuffer(mCore->mAllocator->createGraphicBuffer(
  873. allocWidth, allocHeight, allocFormat, allocUsage, &result));
  874. if (result != NO_ERROR) {
  875. BQ_LOGE("allocateBuffers: failed to allocate buffer (%u x %u, format"
  876. " %u, usage %u)", width, height, format, usage);
  877. Mutex::Autolock lock(mCore->mMutex);
  878. mCore->mIsAllocating = false;
  879. mCore->mIsAllocatingCondition.broadcast();
  880. return;
  881. }
  882. buffers.push_back(graphicBuffer);
  883. }
  884. { // Autolock scope
  885. Mutex::Autolock lock(mCore->mMutex);
  886. uint32_t checkWidth = width > 0 ? width : mCore->mDefaultWidth;
  887. uint32_t checkHeight = height > 0 ? height : mCore->mDefaultHeight;
  888. PixelFormat checkFormat = format != 0 ?
  889. format : mCore->mDefaultBufferFormat;
  890. uint32_t checkUsage = usage | mCore->mConsumerUsageBits;
  891. if (checkWidth != allocWidth || checkHeight != allocHeight ||
  892. checkFormat != allocFormat || checkUsage != allocUsage) {
  893. // Something changed while we released the lock. Retry.
  894. BQ_LOGV("allocateBuffers: size/format/usage changed while allocating. Retrying.");
  895. mCore->mIsAllocating = false;
  896. mCore->mIsAllocatingCondition.broadcast();
  897. continue;
  898. }
  899. for (size_t i = 0; i < newBufferCount; ++i) {
  900. int slot = freeSlots[i];
  901. if (mSlots[slot].mBufferState != BufferSlot::FREE) {
  902. // A consumer allocated the FREE slot with attachBuffer. Discard the buffer we
  903. // allocated.
  904. BQ_LOGV("allocateBuffers: slot %d was acquired while allocating. "
  905. "Dropping allocated buffer.", slot);
  906. continue;
  907. }
  908. mCore->freeBufferLocked(slot); // Clean up the slot first
  909. mSlots[slot].mGraphicBuffer = buffers[i];
  910. mSlots[slot].mFence = Fence::NO_FENCE;
  911. // freeBufferLocked puts this slot on the free slots list. Since
  912. // we then attached a buffer, move the slot to free buffer list.
  913. mCore->mFreeSlots.erase(slot);
  914. mCore->mFreeBuffers.push_front(slot);
  915. BQ_LOGV("allocateBuffers: allocated a new buffer in slot %d", slot);
  916. }
  917. mCore->mIsAllocating = false;
  918. mCore->mIsAllocatingCondition.broadcast();
  919. mCore->validateConsistencyLocked();
  920. } // Autolock scope
  921. }
  922. }
  923. status_t BufferQueueProducer::allowAllocation(bool allow) {
  924. ATRACE_CALL();
  925. BQ_LOGV("allowAllocation: %s", allow ? "true" : "false");
  926. Mutex::Autolock lock(mCore->mMutex);
  927. mCore->mAllowAllocation = allow;
  928. return NO_ERROR;
  929. }
  930. status_t BufferQueueProducer::setGenerationNumber(uint32_t generationNumber) {
  931. ATRACE_CALL();
  932. BQ_LOGV("setGenerationNumber: %u", generationNumber);
  933. Mutex::Autolock lock(mCore->mMutex);
  934. mCore->mGenerationNumber = generationNumber;
  935. return NO_ERROR;
  936. }
  937. String8 BufferQueueProducer::getConsumerName() const {
  938. ATRACE_CALL();
  939. Mutex::Autolock lock(mCore->mMutex);
  940. BQ_LOGV("getConsumerName: %s", mConsumerName.string());
  941. return mConsumerName;
  942. }
  943. void BufferQueueProducer::binderDied(const wp<android::IBinder>& /* who */) {
  944. // If we're here, it means that a producer we were connected to died.
  945. // We're guaranteed that we are still connected to it because we remove
  946. // this callback upon disconnect. It's therefore safe to read mConnectedApi
  947. // without synchronization here.
  948. int api = mCore->mConnectedApi;
  949. disconnect(api);
  950. }
  951. } // namespace android