1 /*
2  * Copyright (C) 2017 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_NDEBUG 0
18 #undef LOG_TAG
19 #define LOG_TAG "BufferLayer"
20 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
21 
22 #include "BufferLayer.h"
23 
24 #include <compositionengine/CompositionEngine.h>
25 #include <compositionengine/Display.h>
26 #include <compositionengine/Layer.h>
27 #include <compositionengine/LayerCreationArgs.h>
28 #include <compositionengine/OutputLayer.h>
29 #include <compositionengine/impl/LayerCompositionState.h>
30 #include <compositionengine/impl/OutputLayerCompositionState.h>
31 #include <cutils/compiler.h>
32 #include <cutils/native_handle.h>
33 #include <cutils/properties.h>
34 #include <gui/BufferItem.h>
35 #include <gui/BufferQueue.h>
36 #include <gui/LayerDebugInfo.h>
37 #include <gui/Surface.h>
38 #include <renderengine/RenderEngine.h>
39 #include <ui/DebugUtils.h>
40 #include <utils/Errors.h>
41 #include <utils/Log.h>
42 #include <utils/NativeHandle.h>
43 #include <utils/StopWatch.h>
44 #include <utils/Trace.h>
45 
46 #include <cmath>
47 #include <cstdlib>
48 #include <mutex>
49 #include <sstream>
50 
51 #include "Colorizer.h"
52 #include "DisplayDevice.h"
53 #include "LayerRejecter.h"
54 #include "TimeStats/TimeStats.h"
55 
56 namespace android {
57 
BufferLayer(const LayerCreationArgs & args)58 BufferLayer::BufferLayer(const LayerCreationArgs& args)
59       : Layer(args),
60         mTextureName(args.flinger->getNewTexture()),
61         mCompositionLayer{mFlinger->getCompositionEngine().createLayer(
62                 compositionengine::LayerCreationArgs{this})} {
63     ALOGV("Creating Layer %s", args.name.string());
64 
65     mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
66 
67     mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
68     mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
69 }
70 
~BufferLayer()71 BufferLayer::~BufferLayer() {
72     mFlinger->deleteTextureAsync(mTextureName);
73     mFlinger->mTimeStats->onDestroy(getSequence());
74 }
75 
useSurfaceDamage()76 void BufferLayer::useSurfaceDamage() {
77     if (mFlinger->mForceFullDamage) {
78         surfaceDamageRegion = Region::INVALID_REGION;
79     } else {
80         surfaceDamageRegion = getDrawingSurfaceDamage();
81     }
82 }
83 
useEmptyDamage()84 void BufferLayer::useEmptyDamage() {
85     surfaceDamageRegion.clear();
86 }
87 
isOpaque(const Layer::State & s) const88 bool BufferLayer::isOpaque(const Layer::State& s) const {
89     // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
90     // layer's opaque flag.
91     if ((mSidebandStream == nullptr) && (mActiveBuffer == nullptr)) {
92         return false;
93     }
94 
95     // if the layer has the opaque flag, then we're always opaque,
96     // otherwise we use the current buffer's format.
97     return ((s.flags & layer_state_t::eLayerOpaque) != 0) || getOpacityForFormat(getPixelFormat());
98 }
99 
isVisible() const100 bool BufferLayer::isVisible() const {
101     bool visible = !(isHiddenByPolicy()) && getAlpha() > 0.0f &&
102             (mActiveBuffer != nullptr || mSidebandStream != nullptr);
103     mFlinger->mScheduler->setLayerVisibility(mSchedulerLayerHandle, visible);
104 
105     return visible;
106 }
107 
isFixedSize() const108 bool BufferLayer::isFixedSize() const {
109     return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
110 }
111 
usesSourceCrop() const112 bool BufferLayer::usesSourceCrop() const {
113     return true;
114 }
115 
inverseOrientation(uint32_t transform)116 static constexpr mat4 inverseOrientation(uint32_t transform) {
117     const mat4 flipH(-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
118     const mat4 flipV(1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1);
119     const mat4 rot90(0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
120     mat4 tr;
121 
122     if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
123         tr = tr * rot90;
124     }
125     if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
126         tr = tr * flipH;
127     }
128     if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
129         tr = tr * flipV;
130     }
131     return inverse(tr);
132 }
133 
prepareClientLayer(const RenderArea & renderArea,const Region & clip,bool useIdentityTransform,Region & clearRegion,const bool supportProtectedContent,renderengine::LayerSettings & layer)134 bool BufferLayer::prepareClientLayer(const RenderArea& renderArea, const Region& clip,
135                                      bool useIdentityTransform, Region& clearRegion,
136                                      const bool supportProtectedContent,
137                                      renderengine::LayerSettings& layer) {
138     ATRACE_CALL();
139     Layer::prepareClientLayer(renderArea, clip, useIdentityTransform, clearRegion,
140                               supportProtectedContent, layer);
141     if (CC_UNLIKELY(mActiveBuffer == 0)) {
142         // the texture has not been created yet, this Layer has
143         // in fact never been drawn into. This happens frequently with
144         // SurfaceView because the WindowManager can't know when the client
145         // has drawn the first time.
146 
147         // If there is nothing under us, we paint the screen in black, otherwise
148         // we just skip this update.
149 
150         // figure out if there is something below us
151         Region under;
152         bool finished = false;
153         mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
154             if (finished || layer == static_cast<BufferLayer const*>(this)) {
155                 finished = true;
156                 return;
157             }
158             under.orSelf(layer->visibleRegion);
159         });
160         // if not everything below us is covered, we plug the holes!
161         Region holes(clip.subtract(under));
162         if (!holes.isEmpty()) {
163             clearRegion.orSelf(holes);
164         }
165         return false;
166     }
167     bool blackOutLayer =
168             (isProtected() && !supportProtectedContent) || (isSecure() && !renderArea.isSecure());
169     const State& s(getDrawingState());
170     if (!blackOutLayer) {
171         layer.source.buffer.buffer = mActiveBuffer;
172         layer.source.buffer.isOpaque = isOpaque(s);
173         layer.source.buffer.fence = mActiveBufferFence;
174         layer.source.buffer.textureName = mTextureName;
175         layer.source.buffer.usePremultipliedAlpha = getPremultipledAlpha();
176         layer.source.buffer.isY410BT2020 = isHdrY410();
177         // TODO: we could be more subtle with isFixedSize()
178         const bool useFiltering = needsFiltering(renderArea.getDisplayDevice()) ||
179                 renderArea.needsFiltering() || isFixedSize();
180 
181         // Query the texture matrix given our current filtering mode.
182         float textureMatrix[16];
183         setFilteringEnabled(useFiltering);
184         getDrawingTransformMatrix(textureMatrix);
185 
186         if (getTransformToDisplayInverse()) {
187             /*
188              * the code below applies the primary display's inverse transform to
189              * the texture transform
190              */
191             uint32_t transform = DisplayDevice::getPrimaryDisplayOrientationTransform();
192             mat4 tr = inverseOrientation(transform);
193 
194             /**
195              * TODO(b/36727915): This is basically a hack.
196              *
197              * Ensure that regardless of the parent transformation,
198              * this buffer is always transformed from native display
199              * orientation to display orientation. For example, in the case
200              * of a camera where the buffer remains in native orientation,
201              * we want the pixels to always be upright.
202              */
203             sp<Layer> p = mDrawingParent.promote();
204             if (p != nullptr) {
205                 const auto parentTransform = p->getTransform();
206                 tr = tr * inverseOrientation(parentTransform.getOrientation());
207             }
208 
209             // and finally apply it to the original texture matrix
210             const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
211             memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
212         }
213 
214         const Rect win{getBounds()};
215         float bufferWidth = getBufferSize(s).getWidth();
216         float bufferHeight = getBufferSize(s).getHeight();
217 
218         // BufferStateLayers can have a "buffer size" of [0, 0, -1, -1] when no display frame has
219         // been set and there is no parent layer bounds. In that case, the scale is meaningless so
220         // ignore them.
221         if (!getBufferSize(s).isValid()) {
222             bufferWidth = float(win.right) - float(win.left);
223             bufferHeight = float(win.bottom) - float(win.top);
224         }
225 
226         const float scaleHeight = (float(win.bottom) - float(win.top)) / bufferHeight;
227         const float scaleWidth = (float(win.right) - float(win.left)) / bufferWidth;
228         const float translateY = float(win.top) / bufferHeight;
229         const float translateX = float(win.left) / bufferWidth;
230 
231         // Flip y-coordinates because GLConsumer expects OpenGL convention.
232         mat4 tr = mat4::translate(vec4(.5, .5, 0, 1)) * mat4::scale(vec4(1, -1, 1, 1)) *
233                 mat4::translate(vec4(-.5, -.5, 0, 1)) *
234                 mat4::translate(vec4(translateX, translateY, 0, 1)) *
235                 mat4::scale(vec4(scaleWidth, scaleHeight, 1.0, 1.0));
236 
237         layer.source.buffer.useTextureFiltering = useFiltering;
238         layer.source.buffer.textureTransform = mat4(static_cast<const float*>(textureMatrix)) * tr;
239     } else {
240         // If layer is blacked out, force alpha to 1 so that we draw a black color
241         // layer.
242         layer.source.buffer.buffer = nullptr;
243         layer.alpha = 1.0;
244     }
245 
246     return true;
247 }
248 
isHdrY410() const249 bool BufferLayer::isHdrY410() const {
250     // pixel format is HDR Y410 masquerading as RGBA_1010102
251     return (mCurrentDataSpace == ui::Dataspace::BT2020_ITU_PQ &&
252             getDrawingApi() == NATIVE_WINDOW_API_MEDIA &&
253             getPixelFormat() == HAL_PIXEL_FORMAT_RGBA_1010102);
254 }
255 
getPixelFormat() const256 PixelFormat BufferLayer::getPixelFormat() const {
257     if (!mActiveBuffer) {
258         return PIXEL_FORMAT_NONE;
259     }
260     return mActiveBuffer->format;
261 }
262 
setPerFrameData(const sp<const DisplayDevice> & displayDevice,const ui::Transform & transform,const Rect & viewport,int32_t supportedPerFrameMetadata,const ui::Dataspace targetDataspace)263 void BufferLayer::setPerFrameData(const sp<const DisplayDevice>& displayDevice,
264                                   const ui::Transform& transform, const Rect& viewport,
265                                   int32_t supportedPerFrameMetadata,
266                                   const ui::Dataspace targetDataspace) {
267     RETURN_IF_NO_HWC_LAYER(displayDevice);
268 
269     // Apply this display's projection's viewport to the visible region
270     // before giving it to the HWC HAL.
271     Region visible = transform.transform(visibleRegion.intersect(viewport));
272 
273     const auto outputLayer = findOutputLayerForDisplay(displayDevice);
274     LOG_FATAL_IF(!outputLayer || !outputLayer->getState().hwc);
275 
276     auto& hwcLayer = (*outputLayer->getState().hwc).hwcLayer;
277     auto error = hwcLayer->setVisibleRegion(visible);
278     if (error != HWC2::Error::None) {
279         ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
280               to_string(error).c_str(), static_cast<int32_t>(error));
281         visible.dump(LOG_TAG);
282     }
283     outputLayer->editState().visibleRegion = visible;
284 
285     auto& layerCompositionState = getCompositionLayer()->editState().frontEnd;
286 
287     error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
288     if (error != HWC2::Error::None) {
289         ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
290               to_string(error).c_str(), static_cast<int32_t>(error));
291         surfaceDamageRegion.dump(LOG_TAG);
292     }
293     layerCompositionState.surfaceDamage = surfaceDamageRegion;
294 
295     // Sideband layers
296     if (layerCompositionState.sidebandStream.get()) {
297         setCompositionType(displayDevice, Hwc2::IComposerClient::Composition::SIDEBAND);
298         ALOGV("[%s] Requesting Sideband composition", mName.string());
299         error = hwcLayer->setSidebandStream(layerCompositionState.sidebandStream->handle());
300         if (error != HWC2::Error::None) {
301             ALOGE("[%s] Failed to set sideband stream %p: %s (%d)", mName.string(),
302                   layerCompositionState.sidebandStream->handle(), to_string(error).c_str(),
303                   static_cast<int32_t>(error));
304         }
305         layerCompositionState.compositionType = Hwc2::IComposerClient::Composition::SIDEBAND;
306         return;
307     }
308 
309     // Device or Cursor layers
310     if (mPotentialCursor) {
311         ALOGV("[%s] Requesting Cursor composition", mName.string());
312         setCompositionType(displayDevice, Hwc2::IComposerClient::Composition::CURSOR);
313     } else {
314         ALOGV("[%s] Requesting Device composition", mName.string());
315         setCompositionType(displayDevice, Hwc2::IComposerClient::Composition::DEVICE);
316     }
317 
318     ui::Dataspace dataspace = isColorSpaceAgnostic() && targetDataspace != ui::Dataspace::UNKNOWN
319             ? targetDataspace
320             : mCurrentDataSpace;
321     error = hwcLayer->setDataspace(dataspace);
322     if (error != HWC2::Error::None) {
323         ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(), dataspace,
324               to_string(error).c_str(), static_cast<int32_t>(error));
325     }
326 
327     const HdrMetadata& metadata = getDrawingHdrMetadata();
328     error = hwcLayer->setPerFrameMetadata(supportedPerFrameMetadata, metadata);
329     if (error != HWC2::Error::None && error != HWC2::Error::Unsupported) {
330         ALOGE("[%s] Failed to set hdrMetadata: %s (%d)", mName.string(),
331               to_string(error).c_str(), static_cast<int32_t>(error));
332     }
333 
334     error = hwcLayer->setColorTransform(getColorTransform());
335     if (error == HWC2::Error::Unsupported) {
336         // If per layer color transform is not supported, we use GPU composition.
337         setCompositionType(displayDevice, Hwc2::IComposerClient::Composition::CLIENT);
338     } else if (error != HWC2::Error::None) {
339         ALOGE("[%s] Failed to setColorTransform: %s (%d)", mName.string(),
340                 to_string(error).c_str(), static_cast<int32_t>(error));
341     }
342     layerCompositionState.dataspace = mCurrentDataSpace;
343     layerCompositionState.colorTransform = getColorTransform();
344     layerCompositionState.hdrMetadata = metadata;
345 
346     setHwcLayerBuffer(displayDevice);
347 }
348 
onPreComposition(nsecs_t refreshStartTime)349 bool BufferLayer::onPreComposition(nsecs_t refreshStartTime) {
350     if (mBufferLatched) {
351         Mutex::Autolock lock(mFrameEventHistoryMutex);
352         mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
353     }
354     mRefreshPending = false;
355     return hasReadyFrame();
356 }
357 
onPostComposition(const std::optional<DisplayId> & displayId,const std::shared_ptr<FenceTime> & glDoneFence,const std::shared_ptr<FenceTime> & presentFence,const CompositorTiming & compositorTiming)358 bool BufferLayer::onPostComposition(const std::optional<DisplayId>& displayId,
359                                     const std::shared_ptr<FenceTime>& glDoneFence,
360                                     const std::shared_ptr<FenceTime>& presentFence,
361                                     const CompositorTiming& compositorTiming) {
362     // mFrameLatencyNeeded is true when a new frame was latched for the
363     // composition.
364     if (!mFrameLatencyNeeded) return false;
365 
366     // Update mFrameEventHistory.
367     {
368         Mutex::Autolock lock(mFrameEventHistoryMutex);
369         mFrameEventHistory.addPostComposition(mCurrentFrameNumber, glDoneFence, presentFence,
370                                               compositorTiming);
371     }
372 
373     // Update mFrameTracker.
374     nsecs_t desiredPresentTime = getDesiredPresentTime();
375     mFrameTracker.setDesiredPresentTime(desiredPresentTime);
376 
377     const int32_t layerID = getSequence();
378     mFlinger->mTimeStats->setDesiredTime(layerID, mCurrentFrameNumber, desiredPresentTime);
379 
380     std::shared_ptr<FenceTime> frameReadyFence = getCurrentFenceTime();
381     if (frameReadyFence->isValid()) {
382         mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
383     } else {
384         // There was no fence for this frame, so assume that it was ready
385         // to be presented at the desired present time.
386         mFrameTracker.setFrameReadyTime(desiredPresentTime);
387     }
388 
389     if (presentFence->isValid()) {
390         mFlinger->mTimeStats->setPresentFence(layerID, mCurrentFrameNumber, presentFence);
391         mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
392     } else if (displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
393         // The HWC doesn't support present fences, so use the refresh
394         // timestamp instead.
395         const nsecs_t actualPresentTime = mFlinger->getHwComposer().getRefreshTimestamp(*displayId);
396         mFlinger->mTimeStats->setPresentTime(layerID, mCurrentFrameNumber, actualPresentTime);
397         mFrameTracker.setActualPresentTime(actualPresentTime);
398     }
399 
400     mFrameTracker.advanceFrame();
401     mFrameLatencyNeeded = false;
402     return true;
403 }
404 
latchBuffer(bool & recomputeVisibleRegions,nsecs_t latchTime)405 bool BufferLayer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
406     ATRACE_CALL();
407 
408     bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
409 
410     if (refreshRequired) {
411         return refreshRequired;
412     }
413 
414     if (!hasReadyFrame()) {
415         return false;
416     }
417 
418     // if we've already called updateTexImage() without going through
419     // a composition step, we have to skip this layer at this point
420     // because we cannot call updateTeximage() without a corresponding
421     // compositionComplete() call.
422     // we'll trigger an update in onPreComposition().
423     if (mRefreshPending) {
424         return false;
425     }
426 
427     // If the head buffer's acquire fence hasn't signaled yet, return and
428     // try again later
429     if (!fenceHasSignaled()) {
430         ATRACE_NAME("!fenceHasSignaled()");
431         mFlinger->signalLayerUpdate();
432         return false;
433     }
434 
435     // Capture the old state of the layer for comparisons later
436     const State& s(getDrawingState());
437     const bool oldOpacity = isOpaque(s);
438     sp<GraphicBuffer> oldBuffer = mActiveBuffer;
439 
440     if (!allTransactionsSignaled()) {
441         mFlinger->setTransactionFlags(eTraversalNeeded);
442         return false;
443     }
444 
445     status_t err = updateTexImage(recomputeVisibleRegions, latchTime);
446     if (err != NO_ERROR) {
447         return false;
448     }
449 
450     err = updateActiveBuffer();
451     if (err != NO_ERROR) {
452         return false;
453     }
454 
455     mBufferLatched = true;
456 
457     err = updateFrameNumber(latchTime);
458     if (err != NO_ERROR) {
459         return false;
460     }
461 
462     mRefreshPending = true;
463     mFrameLatencyNeeded = true;
464     if (oldBuffer == nullptr) {
465         // the first time we receive a buffer, we need to trigger a
466         // geometry invalidation.
467         recomputeVisibleRegions = true;
468     }
469 
470     ui::Dataspace dataSpace = getDrawingDataSpace();
471     // translate legacy dataspaces to modern dataspaces
472     switch (dataSpace) {
473         case ui::Dataspace::SRGB:
474             dataSpace = ui::Dataspace::V0_SRGB;
475             break;
476         case ui::Dataspace::SRGB_LINEAR:
477             dataSpace = ui::Dataspace::V0_SRGB_LINEAR;
478             break;
479         case ui::Dataspace::JFIF:
480             dataSpace = ui::Dataspace::V0_JFIF;
481             break;
482         case ui::Dataspace::BT601_625:
483             dataSpace = ui::Dataspace::V0_BT601_625;
484             break;
485         case ui::Dataspace::BT601_525:
486             dataSpace = ui::Dataspace::V0_BT601_525;
487             break;
488         case ui::Dataspace::BT709:
489             dataSpace = ui::Dataspace::V0_BT709;
490             break;
491         default:
492             break;
493     }
494     mCurrentDataSpace = dataSpace;
495 
496     Rect crop(getDrawingCrop());
497     const uint32_t transform(getDrawingTransform());
498     const uint32_t scalingMode(getDrawingScalingMode());
499     const bool transformToDisplayInverse(getTransformToDisplayInverse());
500     if ((crop != mCurrentCrop) || (transform != mCurrentTransform) ||
501         (scalingMode != mCurrentScalingMode) ||
502         (transformToDisplayInverse != mTransformToDisplayInverse)) {
503         mCurrentCrop = crop;
504         mCurrentTransform = transform;
505         mCurrentScalingMode = scalingMode;
506         mTransformToDisplayInverse = transformToDisplayInverse;
507         recomputeVisibleRegions = true;
508     }
509 
510     if (oldBuffer != nullptr) {
511         uint32_t bufWidth = mActiveBuffer->getWidth();
512         uint32_t bufHeight = mActiveBuffer->getHeight();
513         if (bufWidth != uint32_t(oldBuffer->width) || bufHeight != uint32_t(oldBuffer->height)) {
514             recomputeVisibleRegions = true;
515         }
516     }
517 
518     if (oldOpacity != isOpaque(s)) {
519         recomputeVisibleRegions = true;
520     }
521 
522     // Remove any sync points corresponding to the buffer which was just
523     // latched
524     {
525         Mutex::Autolock lock(mLocalSyncPointMutex);
526         auto point = mLocalSyncPoints.begin();
527         while (point != mLocalSyncPoints.end()) {
528             if (!(*point)->frameIsAvailable() || !(*point)->transactionIsApplied()) {
529                 // This sync point must have been added since we started
530                 // latching. Don't drop it yet.
531                 ++point;
532                 continue;
533             }
534 
535             if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
536                 std::stringstream ss;
537                 ss << "Dropping sync point " << (*point)->getFrameNumber();
538                 ATRACE_NAME(ss.str().c_str());
539                 point = mLocalSyncPoints.erase(point);
540             } else {
541                 ++point;
542             }
543         }
544     }
545 
546     return true;
547 }
548 
549 // transaction
notifyAvailableFrames()550 void BufferLayer::notifyAvailableFrames() {
551     const auto headFrameNumber = getHeadFrameNumber();
552     const bool headFenceSignaled = fenceHasSignaled();
553     const bool presentTimeIsCurrent = framePresentTimeIsCurrent();
554     Mutex::Autolock lock(mLocalSyncPointMutex);
555     for (auto& point : mLocalSyncPoints) {
556         if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled &&
557             presentTimeIsCurrent) {
558             point->setFrameAvailable();
559             sp<Layer> requestedSyncLayer = point->getRequestedSyncLayer();
560             if (requestedSyncLayer) {
561                 // Need to update the transaction flag to ensure the layer's pending transaction
562                 // gets applied.
563                 requestedSyncLayer->setTransactionFlags(eTransactionNeeded);
564             }
565         }
566     }
567 }
568 
hasReadyFrame() const569 bool BufferLayer::hasReadyFrame() const {
570     return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
571 }
572 
getEffectiveScalingMode() const573 uint32_t BufferLayer::getEffectiveScalingMode() const {
574     if (mOverrideScalingMode >= 0) {
575         return mOverrideScalingMode;
576     }
577 
578     return mCurrentScalingMode;
579 }
580 
isProtected() const581 bool BufferLayer::isProtected() const {
582     const sp<GraphicBuffer>& buffer(mActiveBuffer);
583     return (buffer != 0) && (buffer->getUsage() & GRALLOC_USAGE_PROTECTED);
584 }
585 
latchUnsignaledBuffers()586 bool BufferLayer::latchUnsignaledBuffers() {
587     static bool propertyLoaded = false;
588     static bool latch = false;
589     static std::mutex mutex;
590     std::lock_guard<std::mutex> lock(mutex);
591     if (!propertyLoaded) {
592         char value[PROPERTY_VALUE_MAX] = {};
593         property_get("debug.sf.latch_unsignaled", value, "0");
594         latch = atoi(value);
595         propertyLoaded = true;
596     }
597     return latch;
598 }
599 
600 // h/w composer set-up
allTransactionsSignaled()601 bool BufferLayer::allTransactionsSignaled() {
602     auto headFrameNumber = getHeadFrameNumber();
603     bool matchingFramesFound = false;
604     bool allTransactionsApplied = true;
605     Mutex::Autolock lock(mLocalSyncPointMutex);
606 
607     for (auto& point : mLocalSyncPoints) {
608         if (point->getFrameNumber() > headFrameNumber) {
609             break;
610         }
611         matchingFramesFound = true;
612 
613         if (!point->frameIsAvailable()) {
614             // We haven't notified the remote layer that the frame for
615             // this point is available yet. Notify it now, and then
616             // abort this attempt to latch.
617             point->setFrameAvailable();
618             allTransactionsApplied = false;
619             break;
620         }
621 
622         allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
623     }
624     return !matchingFramesFound || allTransactionsApplied;
625 }
626 
627 // As documented in libhardware header, formats in the range
628 // 0x100 - 0x1FF are specific to the HAL implementation, and
629 // are known to have no alpha channel
630 // TODO: move definition for device-specific range into
631 // hardware.h, instead of using hard-coded values here.
632 #define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
633 
getOpacityForFormat(uint32_t format)634 bool BufferLayer::getOpacityForFormat(uint32_t format) {
635     if (HARDWARE_IS_DEVICE_FORMAT(format)) {
636         return true;
637     }
638     switch (format) {
639         case HAL_PIXEL_FORMAT_RGBA_8888:
640         case HAL_PIXEL_FORMAT_BGRA_8888:
641         case HAL_PIXEL_FORMAT_RGBA_FP16:
642         case HAL_PIXEL_FORMAT_RGBA_1010102:
643             return false;
644     }
645     // in all other case, we have no blending (also for unknown formats)
646     return true;
647 }
648 
needsFiltering(const sp<const DisplayDevice> & displayDevice) const649 bool BufferLayer::needsFiltering(const sp<const DisplayDevice>& displayDevice) const {
650     // If we are not capturing based on the state of a known display device, we
651     // only return mNeedsFiltering
652     if (displayDevice == nullptr) {
653         return mNeedsFiltering;
654     }
655 
656     const auto outputLayer = findOutputLayerForDisplay(displayDevice);
657     if (outputLayer == nullptr) {
658         return mNeedsFiltering;
659     }
660 
661     const auto& compositionState = outputLayer->getState();
662     const auto displayFrame = compositionState.displayFrame;
663     const auto sourceCrop = compositionState.sourceCrop;
664     return mNeedsFiltering || sourceCrop.getHeight() != displayFrame.getHeight() ||
665             sourceCrop.getWidth() != displayFrame.getWidth();
666 }
667 
getHeadFrameNumber() const668 uint64_t BufferLayer::getHeadFrameNumber() const {
669     if (hasFrameUpdate()) {
670         return getFrameNumber();
671     } else {
672         return mCurrentFrameNumber;
673     }
674 }
675 
getBufferSize(const State & s) const676 Rect BufferLayer::getBufferSize(const State& s) const {
677     // If we have a sideband stream, or we are scaling the buffer then return the layer size since
678     // we cannot determine the buffer size.
679     if ((s.sidebandStream != nullptr) ||
680         (getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE)) {
681         return Rect(getActiveWidth(s), getActiveHeight(s));
682     }
683 
684     if (mActiveBuffer == nullptr) {
685         return Rect::INVALID_RECT;
686     }
687 
688     uint32_t bufWidth = mActiveBuffer->getWidth();
689     uint32_t bufHeight = mActiveBuffer->getHeight();
690 
691     // Undo any transformations on the buffer and return the result.
692     if (mCurrentTransform & ui::Transform::ROT_90) {
693         std::swap(bufWidth, bufHeight);
694     }
695 
696     if (getTransformToDisplayInverse()) {
697         uint32_t invTransform = DisplayDevice::getPrimaryDisplayOrientationTransform();
698         if (invTransform & ui::Transform::ROT_90) {
699             std::swap(bufWidth, bufHeight);
700         }
701     }
702 
703     return Rect(bufWidth, bufHeight);
704 }
705 
getCompositionLayer() const706 std::shared_ptr<compositionengine::Layer> BufferLayer::getCompositionLayer() const {
707     return mCompositionLayer;
708 }
709 
computeSourceBounds(const FloatRect & parentBounds) const710 FloatRect BufferLayer::computeSourceBounds(const FloatRect& parentBounds) const {
711     const State& s(getDrawingState());
712 
713     // If we have a sideband stream, or we are scaling the buffer then return the layer size since
714     // we cannot determine the buffer size.
715     if ((s.sidebandStream != nullptr) ||
716         (getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE)) {
717         return FloatRect(0, 0, getActiveWidth(s), getActiveHeight(s));
718     }
719 
720     if (mActiveBuffer == nullptr) {
721         return parentBounds;
722     }
723 
724     uint32_t bufWidth = mActiveBuffer->getWidth();
725     uint32_t bufHeight = mActiveBuffer->getHeight();
726 
727     // Undo any transformations on the buffer and return the result.
728     if (mCurrentTransform & ui::Transform::ROT_90) {
729         std::swap(bufWidth, bufHeight);
730     }
731 
732     if (getTransformToDisplayInverse()) {
733         uint32_t invTransform = DisplayDevice::getPrimaryDisplayOrientationTransform();
734         if (invTransform & ui::Transform::ROT_90) {
735             std::swap(bufWidth, bufHeight);
736         }
737     }
738 
739     return FloatRect(0, 0, bufWidth, bufHeight);
740 }
741 
742 } // namespace android
743 
744 #if defined(__gl_h_)
745 #error "don't include gl/gl.h in this file"
746 #endif
747 
748 #if defined(__gl2_h_)
749 #error "don't include gl2/gl2.h in this file"
750 #endif
751