1 /*
2  * Copyright (C) 2010 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 #undef LOG_TAG
18 #define LOG_TAG "BufferLayerConsumer"
19 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
20 //#define LOG_NDEBUG 0
21 
22 #include "BufferLayerConsumer.h"
23 
24 #include "DispSync.h"
25 #include "Layer.h"
26 #include "RenderEngine/Image.h"
27 #include "RenderEngine/RenderEngine.h"
28 
29 #include <inttypes.h>
30 
31 #include <cutils/compiler.h>
32 
33 #include <hardware/hardware.h>
34 
35 #include <math/mat4.h>
36 
37 #include <gui/BufferItem.h>
38 #include <gui/GLConsumer.h>
39 #include <gui/ISurfaceComposer.h>
40 #include <gui/SurfaceComposerClient.h>
41 
42 #include <private/gui/ComposerService.h>
43 #include <private/gui/SyncFeatures.h>
44 
45 #include <utils/Log.h>
46 #include <utils/String8.h>
47 #include <utils/Trace.h>
48 
49 namespace android {
50 
51 // Macros for including the BufferLayerConsumer name in log messages
52 #define BLC_LOGV(x, ...) ALOGV("[%s] " x, mName.string(), ##__VA_ARGS__)
53 #define BLC_LOGD(x, ...) ALOGD("[%s] " x, mName.string(), ##__VA_ARGS__)
54 //#define BLC_LOGI(x, ...) ALOGI("[%s] " x, mName.string(), ##__VA_ARGS__)
55 #define BLC_LOGW(x, ...) ALOGW("[%s] " x, mName.string(), ##__VA_ARGS__)
56 #define BLC_LOGE(x, ...) ALOGE("[%s] " x, mName.string(), ##__VA_ARGS__)
57 
58 static const mat4 mtxIdentity;
59 
BufferLayerConsumer(const sp<IGraphicBufferConsumer> & bq,RE::RenderEngine & engine,uint32_t tex,Layer * layer)60 BufferLayerConsumer::BufferLayerConsumer(const sp<IGraphicBufferConsumer>& bq,
61                                          RE::RenderEngine& engine, uint32_t tex, Layer* layer)
62       : ConsumerBase(bq, false),
63         mCurrentCrop(Rect::EMPTY_RECT),
64         mCurrentTransform(0),
65         mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
66         mCurrentFence(Fence::NO_FENCE),
67         mCurrentTimestamp(0),
68         mCurrentDataSpace(ui::Dataspace::UNKNOWN),
69         mCurrentFrameNumber(0),
70         mCurrentTransformToDisplayInverse(false),
71         mCurrentSurfaceDamage(),
72         mCurrentApi(0),
73         mDefaultWidth(1),
74         mDefaultHeight(1),
75         mFilteringEnabled(true),
76         mRE(engine),
77         mTexName(tex),
78         mLayer(layer),
79         mCurrentTexture(BufferQueue::INVALID_BUFFER_SLOT) {
80     BLC_LOGV("BufferLayerConsumer");
81 
82     memcpy(mCurrentTransformMatrix, mtxIdentity.asArray(), sizeof(mCurrentTransformMatrix));
83 
84     mConsumer->setConsumerUsageBits(DEFAULT_USAGE_FLAGS);
85 }
86 
setDefaultBufferSize(uint32_t w,uint32_t h)87 status_t BufferLayerConsumer::setDefaultBufferSize(uint32_t w, uint32_t h) {
88     Mutex::Autolock lock(mMutex);
89     if (mAbandoned) {
90         BLC_LOGE("setDefaultBufferSize: BufferLayerConsumer is abandoned!");
91         return NO_INIT;
92     }
93     mDefaultWidth = w;
94     mDefaultHeight = h;
95     return mConsumer->setDefaultBufferSize(w, h);
96 }
97 
setContentsChangedListener(const wp<ContentsChangedListener> & listener)98 void BufferLayerConsumer::setContentsChangedListener(const wp<ContentsChangedListener>& listener) {
99     setFrameAvailableListener(listener);
100     Mutex::Autolock lock(mMutex);
101     mContentsChangedListener = listener;
102 }
103 
104 // We need to determine the time when a buffer acquired now will be
105 // displayed.  This can be calculated:
106 //   time when previous buffer's actual-present fence was signaled
107 //    + current display refresh rate * HWC latency
108 //    + a little extra padding
109 //
110 // Buffer producers are expected to set their desired presentation time
111 // based on choreographer time stamps, which (coming from vsync events)
112 // will be slightly later then the actual-present timing.  If we get a
113 // desired-present time that is unintentionally a hair after the next
114 // vsync, we'll hold the frame when we really want to display it.  We
115 // need to take the offset between actual-present and reported-vsync
116 // into account.
117 //
118 // If the system is configured without a DispSync phase offset for the app,
119 // we also want to throw in a bit of padding to avoid edge cases where we
120 // just barely miss.  We want to do it here, not in every app.  A major
121 // source of trouble is the app's use of the display's ideal refresh time
122 // (via Display.getRefreshRate()), which could be off of the actual refresh
123 // by a few percent, with the error multiplied by the number of frames
124 // between now and when the buffer should be displayed.
125 //
126 // If the refresh reported to the app has a phase offset, we shouldn't need
127 // to tweak anything here.
computeExpectedPresent(const DispSync & dispSync)128 nsecs_t BufferLayerConsumer::computeExpectedPresent(const DispSync& dispSync) {
129     // The HWC doesn't currently have a way to report additional latency.
130     // Assume that whatever we submit now will appear right after the flip.
131     // For a smart panel this might be 1.  This is expressed in frames,
132     // rather than time, because we expect to have a constant frame delay
133     // regardless of the refresh rate.
134     const uint32_t hwcLatency = 0;
135 
136     // Ask DispSync when the next refresh will be (CLOCK_MONOTONIC).
137     const nsecs_t nextRefresh = dispSync.computeNextRefresh(hwcLatency);
138 
139     // The DispSync time is already adjusted for the difference between
140     // vsync and reported-vsync (SurfaceFlinger::dispSyncPresentTimeOffset), so
141     // we don't need to factor that in here.  Pad a little to avoid
142     // weird effects if apps might be requesting times right on the edge.
143     nsecs_t extraPadding = 0;
144     if (SurfaceFlinger::vsyncPhaseOffsetNs == 0) {
145         extraPadding = 1000000; // 1ms (6% of 60Hz)
146     }
147 
148     return nextRefresh + extraPadding;
149 }
150 
updateTexImage(BufferRejecter * rejecter,const DispSync & dispSync,bool * autoRefresh,bool * queuedBuffer,uint64_t maxFrameNumber)151 status_t BufferLayerConsumer::updateTexImage(BufferRejecter* rejecter, const DispSync& dispSync,
152                                              bool* autoRefresh, bool* queuedBuffer,
153                                              uint64_t maxFrameNumber) {
154     ATRACE_CALL();
155     BLC_LOGV("updateTexImage");
156     Mutex::Autolock lock(mMutex);
157 
158     if (mAbandoned) {
159         BLC_LOGE("updateTexImage: BufferLayerConsumer is abandoned!");
160         return NO_INIT;
161     }
162 
163     // Make sure RenderEngine is current
164     if (!mRE.isCurrent()) {
165         BLC_LOGE("updateTexImage: RenderEngine is not current");
166         return INVALID_OPERATION;
167     }
168 
169     BufferItem item;
170 
171     // Acquire the next buffer.
172     // In asynchronous mode the list is guaranteed to be one buffer
173     // deep, while in synchronous mode we use the oldest buffer.
174     status_t err = acquireBufferLocked(&item, computeExpectedPresent(dispSync), maxFrameNumber);
175     if (err != NO_ERROR) {
176         if (err == BufferQueue::NO_BUFFER_AVAILABLE) {
177             err = NO_ERROR;
178         } else if (err == BufferQueue::PRESENT_LATER) {
179             // return the error, without logging
180         } else {
181             BLC_LOGE("updateTexImage: acquire failed: %s (%d)", strerror(-err), err);
182         }
183         return err;
184     }
185 
186     if (autoRefresh) {
187         *autoRefresh = item.mAutoRefresh;
188     }
189 
190     if (queuedBuffer) {
191         *queuedBuffer = item.mQueuedBuffer;
192     }
193 
194     // We call the rejecter here, in case the caller has a reason to
195     // not accept this buffer.  This is used by SurfaceFlinger to
196     // reject buffers which have the wrong size
197     int slot = item.mSlot;
198     if (rejecter && rejecter->reject(mSlots[slot].mGraphicBuffer, item)) {
199         releaseBufferLocked(slot, mSlots[slot].mGraphicBuffer);
200         return BUFFER_REJECTED;
201     }
202 
203     // Release the previous buffer.
204     err = updateAndReleaseLocked(item, &mPendingRelease);
205     if (err != NO_ERROR) {
206         return err;
207     }
208 
209     if (!SyncFeatures::getInstance().useNativeFenceSync()) {
210         // Bind the new buffer to the GL texture.
211         //
212         // Older devices require the "implicit" synchronization provided
213         // by glEGLImageTargetTexture2DOES, which this method calls.  Newer
214         // devices will either call this in Layer::onDraw, or (if it's not
215         // a GL-composited layer) not at all.
216         err = bindTextureImageLocked();
217     }
218 
219     return err;
220 }
221 
bindTextureImage()222 status_t BufferLayerConsumer::bindTextureImage() {
223     Mutex::Autolock lock(mMutex);
224     return bindTextureImageLocked();
225 }
226 
setReleaseFence(const sp<Fence> & fence)227 void BufferLayerConsumer::setReleaseFence(const sp<Fence>& fence) {
228     if (!fence->isValid()) {
229         return;
230     }
231 
232     auto slot = mPendingRelease.isPending ? mPendingRelease.currentTexture : mCurrentTexture;
233     if (slot == BufferQueue::INVALID_BUFFER_SLOT) {
234         return;
235     }
236 
237     auto buffer = mPendingRelease.isPending ? mPendingRelease.graphicBuffer
238                                             : mCurrentTextureImage->graphicBuffer();
239     auto err = addReleaseFence(slot, buffer, fence);
240     if (err != OK) {
241         BLC_LOGE("setReleaseFence: failed to add the fence: %s (%d)", strerror(-err), err);
242     }
243 }
244 
releasePendingBuffer()245 bool BufferLayerConsumer::releasePendingBuffer() {
246     if (!mPendingRelease.isPending) {
247         BLC_LOGV("Pending buffer already released");
248         return false;
249     }
250     BLC_LOGV("Releasing pending buffer");
251     Mutex::Autolock lock(mMutex);
252     status_t result =
253             releaseBufferLocked(mPendingRelease.currentTexture, mPendingRelease.graphicBuffer);
254     if (result < NO_ERROR) {
255         BLC_LOGE("releasePendingBuffer failed: %s (%d)", strerror(-result), result);
256     }
257     mPendingRelease = PendingRelease();
258     return true;
259 }
260 
getPrevFinalReleaseFence() const261 sp<Fence> BufferLayerConsumer::getPrevFinalReleaseFence() const {
262     Mutex::Autolock lock(mMutex);
263     return ConsumerBase::mPrevFinalReleaseFence;
264 }
265 
acquireBufferLocked(BufferItem * item,nsecs_t presentWhen,uint64_t maxFrameNumber)266 status_t BufferLayerConsumer::acquireBufferLocked(BufferItem* item, nsecs_t presentWhen,
267                                                   uint64_t maxFrameNumber) {
268     status_t err = ConsumerBase::acquireBufferLocked(item, presentWhen, maxFrameNumber);
269     if (err != NO_ERROR) {
270         return err;
271     }
272 
273     // If item->mGraphicBuffer is not null, this buffer has not been acquired
274     // before, so any prior EglImage created is using a stale buffer. This
275     // replaces any old EglImage with a new one (using the new buffer).
276     if (item->mGraphicBuffer != nullptr) {
277         mImages[item->mSlot] = new Image(item->mGraphicBuffer, mRE);
278     }
279 
280     return NO_ERROR;
281 }
282 
canUseImageCrop(const Rect & crop) const283 bool BufferLayerConsumer::canUseImageCrop(const Rect& crop) const {
284     // If the crop rect is not at the origin, we can't set the crop on the
285     // EGLImage because that's not allowed by the EGL_ANDROID_image_crop
286     // extension.  In the future we can add a layered extension that
287     // removes this restriction if there is hardware that can support it.
288     return mRE.supportsImageCrop() && crop.left == 0 && crop.top == 0;
289 }
290 
updateAndReleaseLocked(const BufferItem & item,PendingRelease * pendingRelease)291 status_t BufferLayerConsumer::updateAndReleaseLocked(const BufferItem& item,
292                                                      PendingRelease* pendingRelease) {
293     status_t err = NO_ERROR;
294 
295     int slot = item.mSlot;
296 
297     // Do whatever sync ops we need to do before releasing the old slot.
298     if (slot != mCurrentTexture) {
299         err = syncForReleaseLocked();
300         if (err != NO_ERROR) {
301             // Release the buffer we just acquired.  It's not safe to
302             // release the old buffer, so instead we just drop the new frame.
303             // As we are still under lock since acquireBuffer, it is safe to
304             // release by slot.
305             releaseBufferLocked(slot, mSlots[slot].mGraphicBuffer);
306             return err;
307         }
308     }
309 
310     BLC_LOGV("updateAndRelease: (slot=%d buf=%p) -> (slot=%d buf=%p)", mCurrentTexture,
311              mCurrentTextureImage != nullptr ? mCurrentTextureImage->graphicBufferHandle() : 0,
312              slot, mSlots[slot].mGraphicBuffer->handle);
313 
314     // Hang onto the pointer so that it isn't freed in the call to
315     // releaseBufferLocked() if we're in shared buffer mode and both buffers are
316     // the same.
317     sp<Image> nextTextureImage = mImages[slot];
318 
319     // release old buffer
320     if (mCurrentTexture != BufferQueue::INVALID_BUFFER_SLOT) {
321         if (pendingRelease == nullptr) {
322             status_t status =
323                     releaseBufferLocked(mCurrentTexture, mCurrentTextureImage->graphicBuffer());
324             if (status < NO_ERROR) {
325                 BLC_LOGE("updateAndRelease: failed to release buffer: %s (%d)", strerror(-status),
326                          status);
327                 err = status;
328                 // keep going, with error raised [?]
329             }
330         } else {
331             pendingRelease->currentTexture = mCurrentTexture;
332             pendingRelease->graphicBuffer = mCurrentTextureImage->graphicBuffer();
333             pendingRelease->isPending = true;
334         }
335     }
336 
337     // Update the BufferLayerConsumer state.
338     mCurrentTexture = slot;
339     mCurrentTextureImage = nextTextureImage;
340     mCurrentCrop = item.mCrop;
341     mCurrentTransform = item.mTransform;
342     mCurrentScalingMode = item.mScalingMode;
343     mCurrentTimestamp = item.mTimestamp;
344     mCurrentDataSpace = static_cast<ui::Dataspace>(item.mDataSpace);
345     mCurrentHdrMetadata = item.mHdrMetadata;
346     mCurrentFence = item.mFence;
347     mCurrentFenceTime = item.mFenceTime;
348     mCurrentFrameNumber = item.mFrameNumber;
349     mCurrentTransformToDisplayInverse = item.mTransformToDisplayInverse;
350     mCurrentSurfaceDamage = item.mSurfaceDamage;
351     mCurrentApi = item.mApi;
352 
353     computeCurrentTransformMatrixLocked();
354 
355     return err;
356 }
357 
bindTextureImageLocked()358 status_t BufferLayerConsumer::bindTextureImageLocked() {
359     ATRACE_CALL();
360     mRE.checkErrors();
361 
362     if (mCurrentTexture == BufferQueue::INVALID_BUFFER_SLOT && mCurrentTextureImage == nullptr) {
363         BLC_LOGE("bindTextureImage: no currently-bound texture");
364         mRE.bindExternalTextureImage(mTexName, *mRE.createImage());
365         return NO_INIT;
366     }
367 
368     const Rect& imageCrop = canUseImageCrop(mCurrentCrop) ? mCurrentCrop : Rect::EMPTY_RECT;
369     status_t err = mCurrentTextureImage->createIfNeeded(imageCrop);
370     if (err != NO_ERROR) {
371         BLC_LOGW("bindTextureImage: can't create image on slot=%d", mCurrentTexture);
372         mRE.bindExternalTextureImage(mTexName, *mRE.createImage());
373         return UNKNOWN_ERROR;
374     }
375 
376     mRE.bindExternalTextureImage(mTexName, mCurrentTextureImage->image());
377 
378     // Wait for the new buffer to be ready.
379     return doFenceWaitLocked();
380 }
381 
syncForReleaseLocked()382 status_t BufferLayerConsumer::syncForReleaseLocked() {
383     BLC_LOGV("syncForReleaseLocked");
384 
385     if (mCurrentTexture != BufferQueue::INVALID_BUFFER_SLOT) {
386         if (SyncFeatures::getInstance().useNativeFenceSync()) {
387             base::unique_fd fenceFd = mRE.flush();
388             if (fenceFd == -1) {
389                 BLC_LOGE("syncForReleaseLocked: failed to flush RenderEngine");
390                 return UNKNOWN_ERROR;
391             }
392             sp<Fence> fence(new Fence(std::move(fenceFd)));
393             status_t err = addReleaseFenceLocked(mCurrentTexture,
394                                                  mCurrentTextureImage->graphicBuffer(), fence);
395             if (err != OK) {
396                 BLC_LOGE("syncForReleaseLocked: error adding release fence: "
397                          "%s (%d)",
398                          strerror(-err), err);
399                 return err;
400             }
401         }
402     }
403 
404     return OK;
405 }
406 
getTransformMatrix(float mtx[16])407 void BufferLayerConsumer::getTransformMatrix(float mtx[16]) {
408     Mutex::Autolock lock(mMutex);
409     memcpy(mtx, mCurrentTransformMatrix, sizeof(mCurrentTransformMatrix));
410 }
411 
setFilteringEnabled(bool enabled)412 void BufferLayerConsumer::setFilteringEnabled(bool enabled) {
413     Mutex::Autolock lock(mMutex);
414     if (mAbandoned) {
415         BLC_LOGE("setFilteringEnabled: BufferLayerConsumer is abandoned!");
416         return;
417     }
418     bool needsRecompute = mFilteringEnabled != enabled;
419     mFilteringEnabled = enabled;
420 
421     if (needsRecompute && mCurrentTextureImage == nullptr) {
422         BLC_LOGD("setFilteringEnabled called with mCurrentTextureImage == nullptr");
423     }
424 
425     if (needsRecompute && mCurrentTextureImage != nullptr) {
426         computeCurrentTransformMatrixLocked();
427     }
428 }
429 
computeCurrentTransformMatrixLocked()430 void BufferLayerConsumer::computeCurrentTransformMatrixLocked() {
431     BLC_LOGV("computeCurrentTransformMatrixLocked");
432     sp<GraphicBuffer> buf =
433             (mCurrentTextureImage == nullptr) ? nullptr : mCurrentTextureImage->graphicBuffer();
434     if (buf == nullptr) {
435         BLC_LOGD("computeCurrentTransformMatrixLocked: "
436                  "mCurrentTextureImage is nullptr");
437     }
438     const Rect& cropRect = canUseImageCrop(mCurrentCrop) ? Rect::EMPTY_RECT : mCurrentCrop;
439     GLConsumer::computeTransformMatrix(mCurrentTransformMatrix, buf, cropRect, mCurrentTransform,
440                                        mFilteringEnabled);
441 }
442 
getTimestamp()443 nsecs_t BufferLayerConsumer::getTimestamp() {
444     BLC_LOGV("getTimestamp");
445     Mutex::Autolock lock(mMutex);
446     return mCurrentTimestamp;
447 }
448 
getCurrentDataSpace()449 ui::Dataspace BufferLayerConsumer::getCurrentDataSpace() {
450     BLC_LOGV("getCurrentDataSpace");
451     Mutex::Autolock lock(mMutex);
452     return mCurrentDataSpace;
453 }
454 
getCurrentHdrMetadata() const455 const HdrMetadata& BufferLayerConsumer::getCurrentHdrMetadata() const {
456     BLC_LOGV("getCurrentHdrMetadata");
457     Mutex::Autolock lock(mMutex);
458     return mCurrentHdrMetadata;
459 }
460 
getFrameNumber()461 uint64_t BufferLayerConsumer::getFrameNumber() {
462     BLC_LOGV("getFrameNumber");
463     Mutex::Autolock lock(mMutex);
464     return mCurrentFrameNumber;
465 }
466 
getTransformToDisplayInverse() const467 bool BufferLayerConsumer::getTransformToDisplayInverse() const {
468     Mutex::Autolock lock(mMutex);
469     return mCurrentTransformToDisplayInverse;
470 }
471 
getSurfaceDamage() const472 const Region& BufferLayerConsumer::getSurfaceDamage() const {
473     return mCurrentSurfaceDamage;
474 }
475 
getCurrentApi() const476 int BufferLayerConsumer::getCurrentApi() const {
477     Mutex::Autolock lock(mMutex);
478     return mCurrentApi;
479 }
480 
getCurrentBuffer(int * outSlot) const481 sp<GraphicBuffer> BufferLayerConsumer::getCurrentBuffer(int* outSlot) const {
482     Mutex::Autolock lock(mMutex);
483 
484     if (outSlot != nullptr) {
485         *outSlot = mCurrentTexture;
486     }
487 
488     return (mCurrentTextureImage == nullptr) ? nullptr : mCurrentTextureImage->graphicBuffer();
489 }
490 
getCurrentCrop() const491 Rect BufferLayerConsumer::getCurrentCrop() const {
492     Mutex::Autolock lock(mMutex);
493     return (mCurrentScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP)
494             ? GLConsumer::scaleDownCrop(mCurrentCrop, mDefaultWidth, mDefaultHeight)
495             : mCurrentCrop;
496 }
497 
getCurrentTransform() const498 uint32_t BufferLayerConsumer::getCurrentTransform() const {
499     Mutex::Autolock lock(mMutex);
500     return mCurrentTransform;
501 }
502 
getCurrentScalingMode() const503 uint32_t BufferLayerConsumer::getCurrentScalingMode() const {
504     Mutex::Autolock lock(mMutex);
505     return mCurrentScalingMode;
506 }
507 
getCurrentFence() const508 sp<Fence> BufferLayerConsumer::getCurrentFence() const {
509     Mutex::Autolock lock(mMutex);
510     return mCurrentFence;
511 }
512 
getCurrentFenceTime() const513 std::shared_ptr<FenceTime> BufferLayerConsumer::getCurrentFenceTime() const {
514     Mutex::Autolock lock(mMutex);
515     return mCurrentFenceTime;
516 }
517 
doFenceWaitLocked() const518 status_t BufferLayerConsumer::doFenceWaitLocked() const {
519     if (!mRE.isCurrent()) {
520         BLC_LOGE("doFenceWait: RenderEngine is not current");
521         return INVALID_OPERATION;
522     }
523 
524     if (mCurrentFence->isValid()) {
525         if (SyncFeatures::getInstance().useWaitSync()) {
526             base::unique_fd fenceFd(mCurrentFence->dup());
527             if (fenceFd == -1) {
528                 BLC_LOGE("doFenceWait: error dup'ing fence fd: %d", errno);
529                 return -errno;
530             }
531             if (!mRE.waitFence(std::move(fenceFd))) {
532                 BLC_LOGE("doFenceWait: failed to wait on fence fd");
533                 return UNKNOWN_ERROR;
534             }
535         } else {
536             status_t err = mCurrentFence->waitForever("BufferLayerConsumer::doFenceWaitLocked");
537             if (err != NO_ERROR) {
538                 BLC_LOGE("doFenceWait: error waiting for fence: %d", err);
539                 return err;
540             }
541         }
542     }
543 
544     return NO_ERROR;
545 }
546 
freeBufferLocked(int slotIndex)547 void BufferLayerConsumer::freeBufferLocked(int slotIndex) {
548     BLC_LOGV("freeBufferLocked: slotIndex=%d", slotIndex);
549     if (slotIndex == mCurrentTexture) {
550         mCurrentTexture = BufferQueue::INVALID_BUFFER_SLOT;
551     }
552     mImages[slotIndex].clear();
553     ConsumerBase::freeBufferLocked(slotIndex);
554 }
555 
onDisconnect()556 void BufferLayerConsumer::onDisconnect() {
557     sp<Layer> l = mLayer.promote();
558     if (l.get()) {
559         l->onDisconnect();
560     }
561 }
562 
onSidebandStreamChanged()563 void BufferLayerConsumer::onSidebandStreamChanged() {
564     FrameAvailableListener* unsafeFrameAvailableListener = nullptr;
565     {
566         Mutex::Autolock lock(mFrameAvailableMutex);
567         unsafeFrameAvailableListener = mFrameAvailableListener.unsafe_get();
568     }
569     sp<ContentsChangedListener> listener;
570     { // scope for the lock
571         Mutex::Autolock lock(mMutex);
572         ALOG_ASSERT(unsafeFrameAvailableListener == mContentsChangedListener.unsafe_get());
573         listener = mContentsChangedListener.promote();
574     }
575 
576     if (listener != nullptr) {
577         listener->onSidebandStreamChanged();
578     }
579 }
580 
addAndGetFrameTimestamps(const NewFrameEventsEntry * newTimestamps,FrameEventHistoryDelta * outDelta)581 void BufferLayerConsumer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
582                                                    FrameEventHistoryDelta* outDelta) {
583     sp<Layer> l = mLayer.promote();
584     if (l.get()) {
585         l->addAndGetFrameTimestamps(newTimestamps, outDelta);
586     }
587 }
588 
abandonLocked()589 void BufferLayerConsumer::abandonLocked() {
590     BLC_LOGV("abandonLocked");
591     mCurrentTextureImage.clear();
592     ConsumerBase::abandonLocked();
593 }
594 
setConsumerUsageBits(uint64_t usage)595 status_t BufferLayerConsumer::setConsumerUsageBits(uint64_t usage) {
596     return ConsumerBase::setConsumerUsageBits(usage | DEFAULT_USAGE_FLAGS);
597 }
598 
dumpLocked(String8 & result,const char * prefix) const599 void BufferLayerConsumer::dumpLocked(String8& result, const char* prefix) const {
600     result.appendFormat("%smTexName=%d mCurrentTexture=%d\n"
601                         "%smCurrentCrop=[%d,%d,%d,%d] mCurrentTransform=%#x\n",
602                         prefix, mTexName, mCurrentTexture, prefix, mCurrentCrop.left,
603                         mCurrentCrop.top, mCurrentCrop.right, mCurrentCrop.bottom,
604                         mCurrentTransform);
605 
606     ConsumerBase::dumpLocked(result, prefix);
607 }
608 
Image(sp<GraphicBuffer> graphicBuffer,RE::RenderEngine & engine)609 BufferLayerConsumer::Image::Image(sp<GraphicBuffer> graphicBuffer, RE::RenderEngine& engine)
610       : mGraphicBuffer(graphicBuffer),
611         mImage{engine.createImage()},
612         mCreated(false),
613         mCropWidth(0),
614         mCropHeight(0) {}
615 
616 BufferLayerConsumer::Image::~Image() = default;
617 
createIfNeeded(const Rect & imageCrop)618 status_t BufferLayerConsumer::Image::createIfNeeded(const Rect& imageCrop) {
619     const int32_t cropWidth = imageCrop.width();
620     const int32_t cropHeight = imageCrop.height();
621     if (mCreated && mCropWidth == cropWidth && mCropHeight == cropHeight) {
622         return OK;
623     }
624 
625     mCreated = mImage->setNativeWindowBuffer(mGraphicBuffer->getNativeBuffer(),
626                                              mGraphicBuffer->getUsage() & GRALLOC_USAGE_PROTECTED,
627                                              cropWidth, cropHeight);
628     if (mCreated) {
629         mCropWidth = cropWidth;
630         mCropHeight = cropHeight;
631     } else {
632         mCropWidth = 0;
633         mCropHeight = 0;
634 
635         const sp<GraphicBuffer>& buffer = mGraphicBuffer;
636         ALOGE("Failed to create image. size=%ux%u st=%u usage=%#" PRIx64 " fmt=%d",
637               buffer->getWidth(), buffer->getHeight(), buffer->getStride(), buffer->getUsage(),
638               buffer->getPixelFormat());
639     }
640 
641     return mCreated ? OK : UNKNOWN_ERROR;
642 }
643 
644 }; // namespace android
645