OSDN Git Service

surfaceflinger: make vsync injection more robust
[android-x86/frameworks-native.git] / services / surfaceflinger / Layer.cpp
1 /*
2  * Copyright (C) 2007 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 "Layer"
20 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
21
22 #include <stdlib.h>
23 #include <stdint.h>
24 #include <sys/types.h>
25 #include <math.h>
26
27 #include <cutils/compiler.h>
28 #include <cutils/native_handle.h>
29 #include <cutils/properties.h>
30
31 #include <utils/Errors.h>
32 #include <utils/Log.h>
33 #include <utils/NativeHandle.h>
34 #include <utils/StopWatch.h>
35 #include <utils/Trace.h>
36
37 #include <ui/DebugUtils.h>
38 #include <ui/GraphicBuffer.h>
39 #include <ui/PixelFormat.h>
40
41 #include <gui/BufferItem.h>
42 #include <gui/BufferQueue.h>
43 #include <gui/Surface.h>
44
45 #include "clz.h"
46 #include "Colorizer.h"
47 #include "DisplayDevice.h"
48 #include "Layer.h"
49 #include "LayerRejecter.h"
50 #include "MonitoredProducer.h"
51 #include "SurfaceFlinger.h"
52
53 #include "DisplayHardware/HWComposer.h"
54
55 #include "RenderEngine/RenderEngine.h"
56
57 #include <mutex>
58
59 #define DEBUG_RESIZE    0
60
61 namespace android {
62
63 // ---------------------------------------------------------------------------
64
65 int32_t Layer::sSequence = 1;
66
67 Layer::Layer(SurfaceFlinger* flinger, const sp<Client>& client,
68         const String8& name, uint32_t w, uint32_t h, uint32_t flags)
69     :   contentDirty(false),
70         sequence(uint32_t(android_atomic_inc(&sSequence))),
71         mFlinger(flinger),
72         mTextureName(-1U),
73         mPremultipliedAlpha(true),
74         mName("unnamed"),
75         mFormat(PIXEL_FORMAT_NONE),
76         mTransactionFlags(0),
77         mPendingStateMutex(),
78         mPendingStates(),
79         mQueuedFrames(0),
80         mSidebandStreamChanged(false),
81         mActiveBufferSlot(BufferQueue::INVALID_BUFFER_SLOT),
82         mCurrentTransform(0),
83         mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
84         mOverrideScalingMode(-1),
85         mCurrentOpacity(true),
86         mBufferLatched(false),
87         mCurrentFrameNumber(0),
88         mPreviousFrameNumber(0),
89         mRefreshPending(false),
90         mFrameLatencyNeeded(false),
91         mFiltering(false),
92         mNeedsFiltering(false),
93         mMesh(Mesh::TRIANGLE_FAN, 4, 2, 2),
94 #ifndef USE_HWC2
95         mIsGlesComposition(false),
96 #endif
97         mProtectedByApp(false),
98         mHasSurface(false),
99         mClientRef(client),
100         mPotentialCursor(false),
101         mQueueItemLock(),
102         mQueueItemCondition(),
103         mQueueItems(),
104         mLastFrameNumberReceived(0),
105         mUpdateTexImageFailed(false),
106         mAutoRefresh(false),
107         mFreezeGeometryUpdates(false)
108 {
109 #ifdef USE_HWC2
110     ALOGV("Creating Layer %s", name.string());
111 #endif
112
113     mCurrentCrop.makeInvalid();
114     mFlinger->getRenderEngine().genTextures(1, &mTextureName);
115     mTexture.init(Texture::TEXTURE_EXTERNAL, mTextureName);
116
117     uint32_t layerFlags = 0;
118     if (flags & ISurfaceComposerClient::eHidden)
119         layerFlags |= layer_state_t::eLayerHidden;
120     if (flags & ISurfaceComposerClient::eOpaque)
121         layerFlags |= layer_state_t::eLayerOpaque;
122     if (flags & ISurfaceComposerClient::eSecure)
123         layerFlags |= layer_state_t::eLayerSecure;
124
125     if (flags & ISurfaceComposerClient::eNonPremultiplied)
126         mPremultipliedAlpha = false;
127
128     mName = name;
129     mTransactionName = String8("TX - ") + mName;
130
131     mCurrentState.active.w = w;
132     mCurrentState.active.h = h;
133     mCurrentState.active.transform.set(0, 0);
134     mCurrentState.crop.makeInvalid();
135     mCurrentState.finalCrop.makeInvalid();
136     mCurrentState.requestedFinalCrop = mCurrentState.finalCrop;
137     mCurrentState.requestedCrop = mCurrentState.crop;
138     mCurrentState.z = 0;
139 #ifdef USE_HWC2
140     mCurrentState.alpha = 1.0f;
141 #else
142     mCurrentState.alpha = 0xFF;
143 #endif
144     mCurrentState.layerStack = 0;
145     mCurrentState.flags = layerFlags;
146     mCurrentState.sequence = 0;
147     mCurrentState.requested = mCurrentState.active;
148     mCurrentState.dataSpace = HAL_DATASPACE_UNKNOWN;
149     mCurrentState.appId = 0;
150     mCurrentState.type = 0;
151
152     // drawing state & current state are identical
153     mDrawingState = mCurrentState;
154
155 #ifdef USE_HWC2
156     const auto& hwc = flinger->getHwComposer();
157     const auto& activeConfig = hwc.getActiveConfig(HWC_DISPLAY_PRIMARY);
158     nsecs_t displayPeriod = activeConfig->getVsyncPeriod();
159 #else
160     nsecs_t displayPeriod =
161             flinger->getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
162 #endif
163     mFrameTracker.setDisplayRefreshPeriod(displayPeriod);
164
165     CompositorTiming compositorTiming;
166     flinger->getCompositorTiming(&compositorTiming);
167     mFrameEventHistory.initializeCompositorTiming(compositorTiming);
168 }
169
170 void Layer::onFirstRef() {
171     // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
172     sp<IGraphicBufferProducer> producer;
173     sp<IGraphicBufferConsumer> consumer;
174     BufferQueue::createBufferQueue(&producer, &consumer, true);
175     mProducer = new MonitoredProducer(producer, mFlinger, this);
176     mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName, this);
177     mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
178     mSurfaceFlingerConsumer->setContentsChangedListener(this);
179     mSurfaceFlingerConsumer->setName(mName);
180
181     if (mFlinger->isLayerTripleBufferingDisabled()) {
182         mProducer->setMaxDequeuedBufferCount(2);
183     }
184
185     const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
186     updateTransformHint(hw);
187 }
188
189 Layer::~Layer() {
190   sp<Client> c(mClientRef.promote());
191     if (c != 0) {
192         c->detachLayer(this);
193     }
194
195     for (auto& point : mRemoteSyncPoints) {
196         point->setTransactionApplied();
197     }
198     for (auto& point : mLocalSyncPoints) {
199         point->setFrameAvailable();
200     }
201     mFlinger->deleteTextureAsync(mTextureName);
202     mFrameTracker.logAndResetStats(mName);
203
204 #ifdef USE_HWC2
205     if (!mHwcLayers.empty()) {
206         ALOGE("Found stale hardware composer layers when destroying "
207                 "surface flinger layer %s", mName.string());
208         destroyAllHwcLayers();
209     }
210 #endif
211 }
212
213 // ---------------------------------------------------------------------------
214 // callbacks
215 // ---------------------------------------------------------------------------
216
217 #ifdef USE_HWC2
218 void Layer::onLayerDisplayed(const sp<Fence>& releaseFence) {
219     if (mHwcLayers.empty()) {
220         return;
221     }
222     mSurfaceFlingerConsumer->setReleaseFence(releaseFence);
223 }
224 #else
225 void Layer::onLayerDisplayed(const sp<const DisplayDevice>& /* hw */,
226         HWComposer::HWCLayerInterface* layer) {
227     if (layer) {
228         layer->onDisplayed();
229         mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence());
230     }
231 }
232 #endif
233
234 void Layer::onFrameAvailable(const BufferItem& item) {
235     // Add this buffer from our internal queue tracker
236     { // Autolock scope
237         Mutex::Autolock lock(mQueueItemLock);
238         mFlinger->mInterceptor.saveBufferUpdate(this, item.mGraphicBuffer->getWidth(),
239                 item.mGraphicBuffer->getHeight(), item.mFrameNumber);
240         // Reset the frame number tracker when we receive the first buffer after
241         // a frame number reset
242         if (item.mFrameNumber == 1) {
243             mLastFrameNumberReceived = 0;
244         }
245
246         // Ensure that callbacks are handled in order
247         while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
248             status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
249                     ms2ns(500));
250             if (result != NO_ERROR) {
251                 ALOGE("[%s] Timed out waiting on callback", mName.string());
252             }
253         }
254
255         mQueueItems.push_back(item);
256         android_atomic_inc(&mQueuedFrames);
257
258         // Wake up any pending callbacks
259         mLastFrameNumberReceived = item.mFrameNumber;
260         mQueueItemCondition.broadcast();
261     }
262
263     mFlinger->signalLayerUpdate();
264 }
265
266 void Layer::onFrameReplaced(const BufferItem& item) {
267     { // Autolock scope
268         Mutex::Autolock lock(mQueueItemLock);
269
270         // Ensure that callbacks are handled in order
271         while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
272             status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
273                     ms2ns(500));
274             if (result != NO_ERROR) {
275                 ALOGE("[%s] Timed out waiting on callback", mName.string());
276             }
277         }
278
279         if (mQueueItems.empty()) {
280             ALOGE("Can't replace a frame on an empty queue");
281             return;
282         }
283         mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
284
285         // Wake up any pending callbacks
286         mLastFrameNumberReceived = item.mFrameNumber;
287         mQueueItemCondition.broadcast();
288     }
289 }
290
291 void Layer::onSidebandStreamChanged() {
292     if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
293         // mSidebandStreamChanged was false
294         mFlinger->signalLayerUpdate();
295     }
296 }
297
298 void Layer::onRemovedFromCurrentState() {
299     // the layer is removed from SF mCurrentState to mLayersPendingRemoval
300
301     if (mCurrentState.zOrderRelativeOf != nullptr) {
302         sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
303         if (strongRelative != nullptr) {
304             strongRelative->removeZOrderRelative(this);
305             mFlinger->setTransactionFlags(eTraversalNeeded);
306         }
307         mCurrentState.zOrderRelativeOf = nullptr;
308     }
309
310     for (const auto& child : mCurrentChildren) {
311         child->onRemovedFromCurrentState();
312     }
313 }
314
315 void Layer::onRemoved() {
316     // the layer is removed from SF mLayersPendingRemoval
317
318     mSurfaceFlingerConsumer->abandon();
319 #ifdef USE_HWC2
320     destroyAllHwcLayers();
321 #endif
322
323     for (const auto& child : mCurrentChildren) {
324         child->onRemoved();
325     }
326 }
327
328 // ---------------------------------------------------------------------------
329 // set-up
330 // ---------------------------------------------------------------------------
331
332 const String8& Layer::getName() const {
333     return mName;
334 }
335
336 status_t Layer::setBuffers( uint32_t w, uint32_t h,
337                             PixelFormat format, uint32_t flags)
338 {
339     uint32_t const maxSurfaceDims = min(
340             mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
341
342     // never allow a surface larger than what our underlying GL implementation
343     // can handle.
344     if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
345         ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
346         return BAD_VALUE;
347     }
348
349     mFormat = format;
350
351     mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
352     mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
353     mCurrentOpacity = getOpacityForFormat(format);
354
355     mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
356     mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
357     mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
358
359     return NO_ERROR;
360 }
361
362 sp<IBinder> Layer::getHandle() {
363     Mutex::Autolock _l(mLock);
364
365     LOG_ALWAYS_FATAL_IF(mHasSurface,
366             "Layer::getHandle() has already been called");
367
368     mHasSurface = true;
369
370     return new Handle(mFlinger, this);
371 }
372
373 sp<IGraphicBufferProducer> Layer::getProducer() const {
374     return mProducer;
375 }
376
377 // ---------------------------------------------------------------------------
378 // h/w composer set-up
379 // ---------------------------------------------------------------------------
380
381 #ifdef USE_HWC2
382 bool Layer::createHwcLayer(HWComposer* hwc, int32_t hwcId) {
383     LOG_ALWAYS_FATAL_IF(mHwcLayers.count(hwcId) != 0,
384                 "Already have a layer for hwcId %d", hwcId);
385     HWC2::Layer* layer = hwc->createLayer(hwcId);
386     if (!layer) {
387         return false;
388     }
389     HWCInfo& hwcInfo = mHwcLayers[hwcId];
390     hwcInfo.hwc = hwc;
391     hwcInfo.layer = layer;
392     layer->setLayerDestroyedListener(
393             [this, hwcId] (HWC2::Layer* /*layer*/){mHwcLayers.erase(hwcId);});
394     return true;
395 }
396
397 void Layer::destroyHwcLayer(int32_t hwcId) {
398     if (mHwcLayers.count(hwcId) == 0) {
399         return;
400     }
401     auto& hwcInfo = mHwcLayers[hwcId];
402     LOG_ALWAYS_FATAL_IF(hwcInfo.layer == nullptr,
403             "Attempt to destroy null layer");
404     LOG_ALWAYS_FATAL_IF(hwcInfo.hwc == nullptr, "Missing HWComposer");
405     hwcInfo.hwc->destroyLayer(hwcId, hwcInfo.layer);
406     // The layer destroyed listener should have cleared the entry from
407     // mHwcLayers. Verify that.
408     LOG_ALWAYS_FATAL_IF(mHwcLayers.count(hwcId) != 0,
409             "Stale layer entry in mHwcLayers");
410 }
411
412 void Layer::destroyAllHwcLayers() {
413     size_t numLayers = mHwcLayers.size();
414     for (size_t i = 0; i < numLayers; ++i) {
415         LOG_ALWAYS_FATAL_IF(mHwcLayers.empty(), "destroyAllHwcLayers failed");
416         destroyHwcLayer(mHwcLayers.begin()->first);
417     }
418     LOG_ALWAYS_FATAL_IF(!mHwcLayers.empty(),
419             "All hardware composer layers should have been destroyed");
420 }
421 #endif
422
423 Rect Layer::getContentCrop() const {
424     // this is the crop rectangle that applies to the buffer
425     // itself (as opposed to the window)
426     Rect crop;
427     if (!mCurrentCrop.isEmpty()) {
428         // if the buffer crop is defined, we use that
429         crop = mCurrentCrop;
430     } else if (mActiveBuffer != NULL) {
431         // otherwise we use the whole buffer
432         crop = mActiveBuffer->getBounds();
433     } else {
434         // if we don't have a buffer yet, we use an empty/invalid crop
435         crop.makeInvalid();
436     }
437     return crop;
438 }
439
440 static Rect reduce(const Rect& win, const Region& exclude) {
441     if (CC_LIKELY(exclude.isEmpty())) {
442         return win;
443     }
444     if (exclude.isRect()) {
445         return win.reduce(exclude.getBounds());
446     }
447     return Region(win).subtract(exclude).getBounds();
448 }
449
450 Rect Layer::computeScreenBounds(bool reduceTransparentRegion) const {
451     const Layer::State& s(getDrawingState());
452     Rect win(s.active.w, s.active.h);
453
454     if (!s.crop.isEmpty()) {
455         win.intersect(s.crop, &win);
456     }
457
458     Transform t = getTransform();
459     win = t.transform(win);
460
461     if (!s.finalCrop.isEmpty()) {
462         win.intersect(s.finalCrop, &win);
463     }
464
465     const sp<Layer>& p = mDrawingParent.promote();
466     // Now we need to calculate the parent bounds, so we can clip ourselves to those.
467     // When calculating the parent bounds for purposes of clipping,
468     // we don't need to constrain the parent to its transparent region.
469     // The transparent region is an optimization based on the
470     // buffer contents of the layer, but does not affect the space allocated to
471     // it by policy, and thus children should be allowed to extend into the
472     // parent's transparent region. In fact one of the main uses, is to reduce
473     // buffer allocation size in cases where a child window sits behind a main window
474     // (by marking the hole in the parent window as a transparent region)
475     if (p != nullptr) {
476         Rect bounds = p->computeScreenBounds(false);
477         bounds.intersect(win, &win);
478     }
479
480     if (reduceTransparentRegion) {
481         auto const screenTransparentRegion = t.transform(s.activeTransparentRegion);
482         win = reduce(win, screenTransparentRegion);
483     }
484
485     return win;
486 }
487
488 Rect Layer::computeBounds() const {
489     const Layer::State& s(getDrawingState());
490     return computeBounds(s.activeTransparentRegion);
491 }
492
493 Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
494     const Layer::State& s(getDrawingState());
495     Rect win(s.active.w, s.active.h);
496
497     if (!s.crop.isEmpty()) {
498         win.intersect(s.crop, &win);
499     }
500
501     Rect bounds = win;
502     const auto& p = mDrawingParent.promote();
503     if (p != nullptr) {
504         // Look in computeScreenBounds recursive call for explanation of
505         // why we pass false here.
506         bounds = p->computeScreenBounds(false /* reduceTransparentRegion */);
507     }
508
509     Transform t = getTransform();
510     if (p != nullptr) {
511         win = t.transform(win);
512         win.intersect(bounds, &win);
513         win = t.inverse().transform(win);
514     }
515
516     // subtract the transparent region and snap to the bounds
517     return reduce(win, activeTransparentRegion);
518 }
519
520 Rect Layer::computeInitialCrop(const sp<const DisplayDevice>& hw) const {
521     // the crop is the area of the window that gets cropped, but not
522     // scaled in any ways.
523     const State& s(getDrawingState());
524
525     // apply the projection's clipping to the window crop in
526     // layerstack space, and convert-back to layer space.
527     // if there are no window scaling involved, this operation will map to full
528     // pixels in the buffer.
529     // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
530     // a viewport clipping and a window transform. we should use floating point to fix this.
531
532     Rect activeCrop(s.active.w, s.active.h);
533     if (!s.crop.isEmpty()) {
534         activeCrop.intersect(s.crop, &activeCrop);
535     }
536
537     Transform t = getTransform();
538     activeCrop = t.transform(activeCrop);
539     if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
540         activeCrop.clear();
541     }
542     if (!s.finalCrop.isEmpty()) {
543         if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
544             activeCrop.clear();
545         }
546     }
547     return activeCrop;
548 }
549
550 FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
551     // the content crop is the area of the content that gets scaled to the
552     // layer's size. This is in buffer space.
553     FloatRect crop = getContentCrop().toFloatRect();
554
555     // In addition there is a WM-specified crop we pull from our drawing state.
556     const State& s(getDrawingState());
557
558     // Screen space to make reduction to parent crop clearer.
559     Rect activeCrop = computeInitialCrop(hw);
560     const auto& p = mDrawingParent.promote();
561     if (p != nullptr) {
562         auto parentCrop = p->computeInitialCrop(hw);
563         activeCrop.intersect(parentCrop, &activeCrop);
564     }
565     Transform t = getTransform();
566     // Back to layer space to work with the content crop.
567     activeCrop = t.inverse().transform(activeCrop);
568
569     // This needs to be here as transform.transform(Rect) computes the
570     // transformed rect and then takes the bounding box of the result before
571     // returning. This means
572     // transform.inverse().transform(transform.transform(Rect)) != Rect
573     // in which case we need to make sure the final rect is clipped to the
574     // display bounds.
575     if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
576         activeCrop.clear();
577     }
578
579     // subtract the transparent region and snap to the bounds
580     activeCrop = reduce(activeCrop, s.activeTransparentRegion);
581
582     // Transform the window crop to match the buffer coordinate system,
583     // which means using the inverse of the current transform set on the
584     // SurfaceFlingerConsumer.
585     uint32_t invTransform = mCurrentTransform;
586     if (getTransformToDisplayInverse()) {
587         /*
588          * the code below applies the primary display's inverse transform to the
589          * buffer
590          */
591         uint32_t invTransformOrient =
592                 DisplayDevice::getPrimaryDisplayOrientationTransform();
593         // calculate the inverse transform
594         if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
595             invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
596                     NATIVE_WINDOW_TRANSFORM_FLIP_H;
597         }
598         // and apply to the current transform
599         invTransform = (Transform(invTransformOrient) * Transform(invTransform))
600                 .getOrientation();
601     }
602
603     int winWidth = s.active.w;
604     int winHeight = s.active.h;
605     if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
606         // If the activeCrop has been rotate the ends are rotated but not
607         // the space itself so when transforming ends back we can't rely on
608         // a modification of the axes of rotation. To account for this we
609         // need to reorient the inverse rotation in terms of the current
610         // axes of rotation.
611         bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
612         bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
613         if (is_h_flipped == is_v_flipped) {
614             invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
615                     NATIVE_WINDOW_TRANSFORM_FLIP_H;
616         }
617         winWidth = s.active.h;
618         winHeight = s.active.w;
619     }
620     const Rect winCrop = activeCrop.transform(
621             invTransform, s.active.w, s.active.h);
622
623     // below, crop is intersected with winCrop expressed in crop's coordinate space
624     float xScale = crop.getWidth()  / float(winWidth);
625     float yScale = crop.getHeight() / float(winHeight);
626
627     float insetL = winCrop.left                 * xScale;
628     float insetT = winCrop.top                  * yScale;
629     float insetR = (winWidth - winCrop.right )  * xScale;
630     float insetB = (winHeight - winCrop.bottom) * yScale;
631
632     crop.left   += insetL;
633     crop.top    += insetT;
634     crop.right  -= insetR;
635     crop.bottom -= insetB;
636
637     return crop;
638 }
639
640 #ifdef USE_HWC2
641 void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice, uint32_t z)
642 #else
643 void Layer::setGeometry(
644     const sp<const DisplayDevice>& hw,
645         HWComposer::HWCLayerInterface& layer)
646 #endif
647 {
648 #ifdef USE_HWC2
649     const auto hwcId = displayDevice->getHwcDisplayId();
650     auto& hwcInfo = mHwcLayers[hwcId];
651 #else
652     layer.setDefaultState();
653 #endif
654
655     // enable this layer
656 #ifdef USE_HWC2
657     hwcInfo.forceClientComposition = false;
658
659     if (isSecure() && !displayDevice->isSecure()) {
660         hwcInfo.forceClientComposition = true;
661     }
662
663     auto& hwcLayer = hwcInfo.layer;
664 #else
665     layer.setSkip(false);
666
667     if (isSecure() && !hw->isSecure()) {
668         layer.setSkip(true);
669     }
670 #endif
671
672     // this gives us only the "orientation" component of the transform
673     const State& s(getDrawingState());
674 #ifdef USE_HWC2
675     auto blendMode = HWC2::BlendMode::None;
676     if (!isOpaque(s) || getAlpha() != 1.0f) {
677         blendMode = mPremultipliedAlpha ?
678                 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
679     }
680     auto error = hwcLayer->setBlendMode(blendMode);
681     ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
682              " %s (%d)", mName.string(), to_string(blendMode).c_str(),
683              to_string(error).c_str(), static_cast<int32_t>(error));
684 #else
685     if (!isOpaque(s) || getAlpha() != 0xFF) {
686         layer.setBlending(mPremultipliedAlpha ?
687                 HWC_BLENDING_PREMULT :
688                 HWC_BLENDING_COVERAGE);
689     }
690 #endif
691
692     // apply the layer's transform, followed by the display's global transform
693     // here we're guaranteed that the layer's transform preserves rects
694     Region activeTransparentRegion(s.activeTransparentRegion);
695     Transform t = getTransform();
696     if (!s.crop.isEmpty()) {
697         Rect activeCrop(s.crop);
698         activeCrop = t.transform(activeCrop);
699 #ifdef USE_HWC2
700         if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
701 #else
702         if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
703 #endif
704             activeCrop.clear();
705         }
706         activeCrop = t.inverse().transform(activeCrop, true);
707         // This needs to be here as transform.transform(Rect) computes the
708         // transformed rect and then takes the bounding box of the result before
709         // returning. This means
710         // transform.inverse().transform(transform.transform(Rect)) != Rect
711         // in which case we need to make sure the final rect is clipped to the
712         // display bounds.
713         if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
714             activeCrop.clear();
715         }
716         // mark regions outside the crop as transparent
717         activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
718         activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
719                 s.active.w, s.active.h));
720         activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
721                 activeCrop.left, activeCrop.bottom));
722         activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
723                 s.active.w, activeCrop.bottom));
724     }
725
726     Rect frame(t.transform(computeBounds(activeTransparentRegion)));
727     if (!s.finalCrop.isEmpty()) {
728         if(!frame.intersect(s.finalCrop, &frame)) {
729             frame.clear();
730         }
731     }
732 #ifdef USE_HWC2
733     if (!frame.intersect(displayDevice->getViewport(), &frame)) {
734         frame.clear();
735     }
736     const Transform& tr(displayDevice->getTransform());
737     Rect transformedFrame = tr.transform(frame);
738     error = hwcLayer->setDisplayFrame(transformedFrame);
739     if (error != HWC2::Error::None) {
740         ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)",
741                 mName.string(), transformedFrame.left, transformedFrame.top,
742                 transformedFrame.right, transformedFrame.bottom,
743                 to_string(error).c_str(), static_cast<int32_t>(error));
744     } else {
745         hwcInfo.displayFrame = transformedFrame;
746     }
747
748     FloatRect sourceCrop = computeCrop(displayDevice);
749     error = hwcLayer->setSourceCrop(sourceCrop);
750     if (error != HWC2::Error::None) {
751         ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
752                 "%s (%d)", mName.string(), sourceCrop.left, sourceCrop.top,
753                 sourceCrop.right, sourceCrop.bottom, to_string(error).c_str(),
754                 static_cast<int32_t>(error));
755     } else {
756         hwcInfo.sourceCrop = sourceCrop;
757     }
758
759     float alpha = getAlpha();
760     error = hwcLayer->setPlaneAlpha(alpha);
761     ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
762             "%s (%d)", mName.string(), alpha, to_string(error).c_str(),
763             static_cast<int32_t>(error));
764
765     error = hwcLayer->setZOrder(z);
766     ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
767             mName.string(), z, to_string(error).c_str(),
768             static_cast<int32_t>(error));
769
770     int type = s.type;
771     int appId = s.appId;
772     sp<Layer> parent = mDrawingParent.promote();
773     if (parent.get()) {
774         auto& parentState = parent->getDrawingState();
775         type = parentState.type;
776         appId = parentState.appId;
777     }
778
779     error = hwcLayer->setInfo(type, appId);
780     ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set info (%d)",
781              mName.string(), static_cast<int32_t>(error));
782 #else
783     if (!frame.intersect(hw->getViewport(), &frame)) {
784         frame.clear();
785     }
786     const Transform& tr(hw->getTransform());
787     layer.setFrame(tr.transform(frame));
788     layer.setCrop(computeCrop(hw));
789     layer.setPlaneAlpha(getAlpha());
790 #endif
791
792     /*
793      * Transformations are applied in this order:
794      * 1) buffer orientation/flip/mirror
795      * 2) state transformation (window manager)
796      * 3) layer orientation (screen orientation)
797      * (NOTE: the matrices are multiplied in reverse order)
798      */
799
800     const Transform bufferOrientation(mCurrentTransform);
801     Transform transform(tr * t * bufferOrientation);
802
803     if (getTransformToDisplayInverse()) {
804         /*
805          * the code below applies the primary display's inverse transform to the
806          * buffer
807          */
808         uint32_t invTransform =
809                 DisplayDevice::getPrimaryDisplayOrientationTransform();
810         // calculate the inverse transform
811         if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
812             invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
813                     NATIVE_WINDOW_TRANSFORM_FLIP_H;
814         }
815
816         /*
817          * Here we cancel out the orientation component of the WM transform.
818          * The scaling and translate components are already included in our bounds
819          * computation so it's enough to just omit it in the composition.
820          * See comment in onDraw with ref to b/36727915 for why.
821          */
822         transform = Transform(invTransform) * tr * bufferOrientation;
823     }
824
825     // this gives us only the "orientation" component of the transform
826     const uint32_t orientation = transform.getOrientation();
827 #ifdef USE_HWC2
828     if (orientation & Transform::ROT_INVALID) {
829         // we can only handle simple transformation
830         hwcInfo.forceClientComposition = true;
831     } else {
832         auto transform = static_cast<HWC2::Transform>(orientation);
833         auto error = hwcLayer->setTransform(transform);
834         ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
835                 "%s (%d)", mName.string(), to_string(transform).c_str(),
836                 to_string(error).c_str(), static_cast<int32_t>(error));
837     }
838 #else
839     if (orientation & Transform::ROT_INVALID) {
840         // we can only handle simple transformation
841         layer.setSkip(true);
842     } else {
843         layer.setTransform(orientation);
844     }
845 #endif
846 }
847
848 #ifdef USE_HWC2
849 void Layer::forceClientComposition(int32_t hwcId) {
850     if (mHwcLayers.count(hwcId) == 0) {
851         ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
852         return;
853     }
854
855     mHwcLayers[hwcId].forceClientComposition = true;
856 }
857
858 void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
859     // Apply this display's projection's viewport to the visible region
860     // before giving it to the HWC HAL.
861     const Transform& tr = displayDevice->getTransform();
862     const auto& viewport = displayDevice->getViewport();
863     Region visible = tr.transform(visibleRegion.intersect(viewport));
864     auto hwcId = displayDevice->getHwcDisplayId();
865     auto& hwcInfo = mHwcLayers[hwcId];
866     auto& hwcLayer = hwcInfo.layer;
867     auto error = hwcLayer->setVisibleRegion(visible);
868     if (error != HWC2::Error::None) {
869         ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
870                 to_string(error).c_str(), static_cast<int32_t>(error));
871         visible.dump(LOG_TAG);
872     }
873
874     error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
875     if (error != HWC2::Error::None) {
876         ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
877                 to_string(error).c_str(), static_cast<int32_t>(error));
878         surfaceDamageRegion.dump(LOG_TAG);
879     }
880
881     // Sideband layers
882     if (mSidebandStream.get()) {
883         setCompositionType(hwcId, HWC2::Composition::Sideband);
884         ALOGV("[%s] Requesting Sideband composition", mName.string());
885         error = hwcLayer->setSidebandStream(mSidebandStream->handle());
886         if (error != HWC2::Error::None) {
887             ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
888                     mName.string(), mSidebandStream->handle(),
889                     to_string(error).c_str(), static_cast<int32_t>(error));
890         }
891         return;
892     }
893
894     // Client layers
895     if (hwcInfo.forceClientComposition ||
896             (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) {
897         ALOGV("[%s] Requesting Client composition", mName.string());
898         setCompositionType(hwcId, HWC2::Composition::Client);
899         return;
900     }
901
902     // SolidColor layers
903     if (mActiveBuffer == nullptr) {
904         setCompositionType(hwcId, HWC2::Composition::SolidColor);
905
906         // For now, we only support black for DimLayer
907         error = hwcLayer->setColor({0, 0, 0, 255});
908         if (error != HWC2::Error::None) {
909             ALOGE("[%s] Failed to set color: %s (%d)", mName.string(),
910                     to_string(error).c_str(), static_cast<int32_t>(error));
911         }
912
913         // Clear out the transform, because it doesn't make sense absent a
914         // source buffer
915         error = hwcLayer->setTransform(HWC2::Transform::None);
916         if (error != HWC2::Error::None) {
917             ALOGE("[%s] Failed to clear transform: %s (%d)", mName.string(),
918                     to_string(error).c_str(), static_cast<int32_t>(error));
919         }
920
921         return;
922     }
923
924     // Device or Cursor layers
925     if (mPotentialCursor) {
926         ALOGV("[%s] Requesting Cursor composition", mName.string());
927         setCompositionType(hwcId, HWC2::Composition::Cursor);
928     } else {
929         ALOGV("[%s] Requesting Device composition", mName.string());
930         setCompositionType(hwcId, HWC2::Composition::Device);
931     }
932
933     ALOGV("setPerFrameData: dataspace = %d", mCurrentState.dataSpace);
934     error = hwcLayer->setDataspace(mCurrentState.dataSpace);
935     if (error != HWC2::Error::None) {
936         ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(),
937               mCurrentState.dataSpace, to_string(error).c_str(),
938               static_cast<int32_t>(error));
939     }
940
941     uint32_t hwcSlot = 0;
942     sp<GraphicBuffer> hwcBuffer;
943     hwcInfo.bufferCache.getHwcBuffer(mActiveBufferSlot, mActiveBuffer,
944             &hwcSlot, &hwcBuffer);
945
946     auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
947     error = hwcLayer->setBuffer(hwcSlot, hwcBuffer, acquireFence);
948     if (error != HWC2::Error::None) {
949         ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
950                 mActiveBuffer->handle, to_string(error).c_str(),
951                 static_cast<int32_t>(error));
952     }
953 }
954
955 #else
956 void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
957         HWComposer::HWCLayerInterface& layer) {
958     // we have to set the visible region on every frame because
959     // we currently free it during onLayerDisplayed(), which is called
960     // after HWComposer::commit() -- every frame.
961     // Apply this display's projection's viewport to the visible region
962     // before giving it to the HWC HAL.
963     const Transform& tr = hw->getTransform();
964     Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
965     layer.setVisibleRegionScreen(visible);
966     layer.setSurfaceDamage(surfaceDamageRegion);
967     mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
968
969     if (mSidebandStream.get()) {
970         layer.setSidebandStream(mSidebandStream);
971     } else {
972         // NOTE: buffer can be NULL if the client never drew into this
973         // layer yet, or if we ran out of memory
974         layer.setBuffer(mActiveBuffer);
975     }
976 }
977 #endif
978
979 #ifdef USE_HWC2
980 void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
981     auto hwcId = displayDevice->getHwcDisplayId();
982     if (mHwcLayers.count(hwcId) == 0 ||
983             getCompositionType(hwcId) != HWC2::Composition::Cursor) {
984         return;
985     }
986
987     // This gives us only the "orientation" component of the transform
988     const State& s(getCurrentState());
989
990     // Apply the layer's transform, followed by the display's global transform
991     // Here we're guaranteed that the layer's transform preserves rects
992     Rect win(s.active.w, s.active.h);
993     if (!s.crop.isEmpty()) {
994         win.intersect(s.crop, &win);
995     }
996     // Subtract the transparent region and snap to the bounds
997     Rect bounds = reduce(win, s.activeTransparentRegion);
998     Rect frame(getTransform().transform(bounds));
999     frame.intersect(displayDevice->getViewport(), &frame);
1000     if (!s.finalCrop.isEmpty()) {
1001         frame.intersect(s.finalCrop, &frame);
1002     }
1003     auto& displayTransform(displayDevice->getTransform());
1004     auto position = displayTransform.transform(frame);
1005
1006     auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
1007             position.top);
1008     ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
1009             "to (%d, %d): %s (%d)", mName.string(), position.left,
1010             position.top, to_string(error).c_str(),
1011             static_cast<int32_t>(error));
1012 }
1013 #else
1014 void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
1015         HWComposer::HWCLayerInterface& layer) {
1016     int fenceFd = -1;
1017
1018     // TODO: there is a possible optimization here: we only need to set the
1019     // acquire fence the first time a new buffer is acquired on EACH display.
1020
1021     if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
1022         sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
1023         if (fence->isValid()) {
1024             fenceFd = fence->dup();
1025             if (fenceFd == -1) {
1026                 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
1027             }
1028         }
1029     }
1030     layer.setAcquireFenceFd(fenceFd);
1031 }
1032
1033 Rect Layer::getPosition(
1034     const sp<const DisplayDevice>& hw)
1035 {
1036     // this gives us only the "orientation" component of the transform
1037     const State& s(getCurrentState());
1038
1039     // apply the layer's transform, followed by the display's global transform
1040     // here we're guaranteed that the layer's transform preserves rects
1041     Rect win(s.active.w, s.active.h);
1042     if (!s.crop.isEmpty()) {
1043         win.intersect(s.crop, &win);
1044     }
1045     // subtract the transparent region and snap to the bounds
1046     Rect bounds = reduce(win, s.activeTransparentRegion);
1047     Rect frame(getTransform().transform(bounds));
1048     frame.intersect(hw->getViewport(), &frame);
1049     if (!s.finalCrop.isEmpty()) {
1050         frame.intersect(s.finalCrop, &frame);
1051     }
1052     const Transform& tr(hw->getTransform());
1053     return Rect(tr.transform(frame));
1054 }
1055 #endif
1056
1057 // ---------------------------------------------------------------------------
1058 // drawing...
1059 // ---------------------------------------------------------------------------
1060
1061 void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
1062     onDraw(hw, clip, false);
1063 }
1064
1065 void Layer::draw(const sp<const DisplayDevice>& hw,
1066         bool useIdentityTransform) const {
1067     onDraw(hw, Region(hw->bounds()), useIdentityTransform);
1068 }
1069
1070 void Layer::draw(const sp<const DisplayDevice>& hw) const {
1071     onDraw(hw, Region(hw->bounds()), false);
1072 }
1073
1074 static constexpr mat4 inverseOrientation(uint32_t transform) {
1075     const mat4 flipH(-1,0,0,0,  0,1,0,0, 0,0,1,0, 1,0,0,1);
1076     const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
1077     const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
1078     mat4 tr;
1079
1080     if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
1081         tr = tr * rot90;
1082     }
1083     if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
1084         tr = tr * flipH;
1085     }
1086     if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
1087         tr = tr * flipV;
1088     }
1089     return inverse(tr);
1090 }
1091
1092 /*
1093  * onDraw will draw the current layer onto the presentable buffer
1094  */
1095 void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
1096         bool useIdentityTransform) const
1097 {
1098     ATRACE_CALL();
1099
1100     if (CC_UNLIKELY(mActiveBuffer == 0)) {
1101         // the texture has not been created yet, this Layer has
1102         // in fact never been drawn into. This happens frequently with
1103         // SurfaceView because the WindowManager can't know when the client
1104         // has drawn the first time.
1105
1106         // If there is nothing under us, we paint the screen in black, otherwise
1107         // we just skip this update.
1108
1109         // figure out if there is something below us
1110         Region under;
1111         bool finished = false;
1112         mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
1113             if (finished || layer == static_cast<Layer const*>(this)) {
1114                 finished = true;
1115                 return;
1116             }
1117             under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
1118         });
1119         // if not everything below us is covered, we plug the holes!
1120         Region holes(clip.subtract(under));
1121         if (!holes.isEmpty()) {
1122             clearWithOpenGL(hw, 0, 0, 0, 1);
1123         }
1124         return;
1125     }
1126
1127     // Bind the current buffer to the GL texture, and wait for it to be
1128     // ready for us to draw into.
1129     status_t err = mSurfaceFlingerConsumer->bindTextureImage();
1130     if (err != NO_ERROR) {
1131         ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
1132         // Go ahead and draw the buffer anyway; no matter what we do the screen
1133         // is probably going to have something visibly wrong.
1134     }
1135
1136     bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
1137
1138     RenderEngine& engine(mFlinger->getRenderEngine());
1139
1140     if (!blackOutLayer) {
1141         // TODO: we could be more subtle with isFixedSize()
1142         const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
1143
1144         // Query the texture matrix given our current filtering mode.
1145         float textureMatrix[16];
1146         mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
1147         mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
1148
1149         if (getTransformToDisplayInverse()) {
1150
1151             /*
1152              * the code below applies the primary display's inverse transform to
1153              * the texture transform
1154              */
1155             uint32_t transform =
1156                     DisplayDevice::getPrimaryDisplayOrientationTransform();
1157             mat4 tr = inverseOrientation(transform);
1158
1159             /**
1160              * TODO(b/36727915): This is basically a hack.
1161              *
1162              * Ensure that regardless of the parent transformation,
1163              * this buffer is always transformed from native display
1164              * orientation to display orientation. For example, in the case
1165              * of a camera where the buffer remains in native orientation,
1166              * we want the pixels to always be upright.
1167              */
1168             sp<Layer> p = mDrawingParent.promote();
1169             if (p != nullptr) {
1170                 const auto parentTransform = p->getTransform();
1171                 tr = tr * inverseOrientation(parentTransform.getOrientation());
1172             }
1173
1174             // and finally apply it to the original texture matrix
1175             const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
1176             memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
1177         }
1178
1179         // Set things up for texturing.
1180         mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
1181         mTexture.setFiltering(useFiltering);
1182         mTexture.setMatrix(textureMatrix);
1183
1184         engine.setupLayerTexturing(mTexture);
1185     } else {
1186         engine.setupLayerBlackedOut();
1187     }
1188     drawWithOpenGL(hw, useIdentityTransform);
1189     engine.disableTexturing();
1190 }
1191
1192
1193 void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
1194         float red, float green, float blue,
1195         float alpha) const
1196 {
1197     RenderEngine& engine(mFlinger->getRenderEngine());
1198     computeGeometry(hw, mMesh, false);
1199     engine.setupFillWithColor(red, green, blue, alpha);
1200     engine.drawMesh(mMesh);
1201 }
1202
1203 void Layer::clearWithOpenGL(
1204         const sp<const DisplayDevice>& hw) const {
1205     clearWithOpenGL(hw, 0,0,0,0);
1206 }
1207
1208 void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
1209         bool useIdentityTransform) const {
1210     const State& s(getDrawingState());
1211
1212     computeGeometry(hw, mMesh, useIdentityTransform);
1213
1214     /*
1215      * NOTE: the way we compute the texture coordinates here produces
1216      * different results than when we take the HWC path -- in the later case
1217      * the "source crop" is rounded to texel boundaries.
1218      * This can produce significantly different results when the texture
1219      * is scaled by a large amount.
1220      *
1221      * The GL code below is more logical (imho), and the difference with
1222      * HWC is due to a limitation of the HWC API to integers -- a question
1223      * is suspend is whether we should ignore this problem or revert to
1224      * GL composition when a buffer scaling is applied (maybe with some
1225      * minimal value)? Or, we could make GL behave like HWC -- but this feel
1226      * like more of a hack.
1227      */
1228     Rect win(computeBounds());
1229
1230     Transform t = getTransform();
1231     if (!s.finalCrop.isEmpty()) {
1232         win = t.transform(win);
1233         if (!win.intersect(s.finalCrop, &win)) {
1234             win.clear();
1235         }
1236         win = t.inverse().transform(win);
1237         if (!win.intersect(computeBounds(), &win)) {
1238             win.clear();
1239         }
1240     }
1241
1242     float left   = float(win.left)   / float(s.active.w);
1243     float top    = float(win.top)    / float(s.active.h);
1244     float right  = float(win.right)  / float(s.active.w);
1245     float bottom = float(win.bottom) / float(s.active.h);
1246
1247     // TODO: we probably want to generate the texture coords with the mesh
1248     // here we assume that we only have 4 vertices
1249     Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1250     texCoords[0] = vec2(left, 1.0f - top);
1251     texCoords[1] = vec2(left, 1.0f - bottom);
1252     texCoords[2] = vec2(right, 1.0f - bottom);
1253     texCoords[3] = vec2(right, 1.0f - top);
1254
1255     RenderEngine& engine(mFlinger->getRenderEngine());
1256     engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), getAlpha());
1257 #ifdef USE_HWC2
1258     engine.setSourceDataSpace(mCurrentState.dataSpace);
1259 #endif
1260     engine.drawMesh(mMesh);
1261     engine.disableBlending();
1262 }
1263
1264 #ifdef USE_HWC2
1265 void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1266         bool callIntoHwc) {
1267     if (mHwcLayers.count(hwcId) == 0) {
1268         ALOGE("setCompositionType called without a valid HWC layer");
1269         return;
1270     }
1271     auto& hwcInfo = mHwcLayers[hwcId];
1272     auto& hwcLayer = hwcInfo.layer;
1273     ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1274             to_string(type).c_str(), static_cast<int>(callIntoHwc));
1275     if (hwcInfo.compositionType != type) {
1276         ALOGV("    actually setting");
1277         hwcInfo.compositionType = type;
1278         if (callIntoHwc) {
1279             auto error = hwcLayer->setCompositionType(type);
1280             ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1281                     "composition type %s: %s (%d)", mName.string(),
1282                     to_string(type).c_str(), to_string(error).c_str(),
1283                     static_cast<int32_t>(error));
1284         }
1285     }
1286 }
1287
1288 HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
1289     if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1290         // If we're querying the composition type for a display that does not
1291         // have a HWC counterpart, then it will always be Client
1292         return HWC2::Composition::Client;
1293     }
1294     if (mHwcLayers.count(hwcId) == 0) {
1295         ALOGE("getCompositionType called with an invalid HWC layer");
1296         return HWC2::Composition::Invalid;
1297     }
1298     return mHwcLayers.at(hwcId).compositionType;
1299 }
1300
1301 void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1302     if (mHwcLayers.count(hwcId) == 0) {
1303         ALOGE("setClearClientTarget called without a valid HWC layer");
1304         return;
1305     }
1306     mHwcLayers[hwcId].clearClientTarget = clear;
1307 }
1308
1309 bool Layer::getClearClientTarget(int32_t hwcId) const {
1310     if (mHwcLayers.count(hwcId) == 0) {
1311         ALOGE("getClearClientTarget called without a valid HWC layer");
1312         return false;
1313     }
1314     return mHwcLayers.at(hwcId).clearClientTarget;
1315 }
1316 #endif
1317
1318 uint32_t Layer::getProducerStickyTransform() const {
1319     int producerStickyTransform = 0;
1320     int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1321     if (ret != OK) {
1322         ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1323                 strerror(-ret), ret);
1324         return 0;
1325     }
1326     return static_cast<uint32_t>(producerStickyTransform);
1327 }
1328
1329 bool Layer::latchUnsignaledBuffers() {
1330     static bool propertyLoaded = false;
1331     static bool latch = false;
1332     static std::mutex mutex;
1333     std::lock_guard<std::mutex> lock(mutex);
1334     if (!propertyLoaded) {
1335         char value[PROPERTY_VALUE_MAX] = {};
1336         property_get("debug.sf.latch_unsignaled", value, "0");
1337         latch = atoi(value);
1338         propertyLoaded = true;
1339     }
1340     return latch;
1341 }
1342
1343 uint64_t Layer::getHeadFrameNumber() const {
1344     Mutex::Autolock lock(mQueueItemLock);
1345     if (!mQueueItems.empty()) {
1346         return mQueueItems[0].mFrameNumber;
1347     } else {
1348         return mCurrentFrameNumber;
1349     }
1350 }
1351
1352 bool Layer::headFenceHasSignaled() const {
1353 #ifdef USE_HWC2
1354     if (latchUnsignaledBuffers()) {
1355         return true;
1356     }
1357
1358     Mutex::Autolock lock(mQueueItemLock);
1359     if (mQueueItems.empty()) {
1360         return true;
1361     }
1362     if (mQueueItems[0].mIsDroppable) {
1363         // Even though this buffer's fence may not have signaled yet, it could
1364         // be replaced by another buffer before it has a chance to, which means
1365         // that it's possible to get into a situation where a buffer is never
1366         // able to be latched. To avoid this, grab this buffer anyway.
1367         return true;
1368     }
1369     return mQueueItems[0].mFenceTime->getSignalTime() !=
1370             Fence::SIGNAL_TIME_PENDING;
1371 #else
1372     return true;
1373 #endif
1374 }
1375
1376 bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1377     if (point->getFrameNumber() <= mCurrentFrameNumber) {
1378         // Don't bother with a SyncPoint, since we've already latched the
1379         // relevant frame
1380         return false;
1381     }
1382
1383     Mutex::Autolock lock(mLocalSyncPointMutex);
1384     mLocalSyncPoints.push_back(point);
1385     return true;
1386 }
1387
1388 void Layer::setFiltering(bool filtering) {
1389     mFiltering = filtering;
1390 }
1391
1392 bool Layer::getFiltering() const {
1393     return mFiltering;
1394 }
1395
1396 // As documented in libhardware header, formats in the range
1397 // 0x100 - 0x1FF are specific to the HAL implementation, and
1398 // are known to have no alpha channel
1399 // TODO: move definition for device-specific range into
1400 // hardware.h, instead of using hard-coded values here.
1401 #define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1402
1403 bool Layer::getOpacityForFormat(uint32_t format) {
1404     if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1405         return true;
1406     }
1407     switch (format) {
1408         case HAL_PIXEL_FORMAT_RGBA_8888:
1409         case HAL_PIXEL_FORMAT_BGRA_8888:
1410         case HAL_PIXEL_FORMAT_RGBA_FP16:
1411         case HAL_PIXEL_FORMAT_RGBA_1010102:
1412             return false;
1413     }
1414     // in all other case, we have no blending (also for unknown formats)
1415     return true;
1416 }
1417
1418 // ----------------------------------------------------------------------------
1419 // local state
1420 // ----------------------------------------------------------------------------
1421
1422 static void boundPoint(vec2* point, const Rect& crop) {
1423     if (point->x < crop.left) {
1424         point->x = crop.left;
1425     }
1426     if (point->x > crop.right) {
1427         point->x = crop.right;
1428     }
1429     if (point->y < crop.top) {
1430         point->y = crop.top;
1431     }
1432     if (point->y > crop.bottom) {
1433         point->y = crop.bottom;
1434     }
1435 }
1436
1437 void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1438         bool useIdentityTransform) const
1439 {
1440     const Layer::State& s(getDrawingState());
1441     const Transform hwTransform(hw->getTransform());
1442     const uint32_t hw_h = hw->getHeight();
1443     Rect win = computeBounds();
1444
1445     vec2 lt = vec2(win.left, win.top);
1446     vec2 lb = vec2(win.left, win.bottom);
1447     vec2 rb = vec2(win.right, win.bottom);
1448     vec2 rt = vec2(win.right, win.top);
1449
1450     Transform layerTransform = getTransform();
1451     if (!useIdentityTransform) {
1452         lt = layerTransform.transform(lt);
1453         lb = layerTransform.transform(lb);
1454         rb = layerTransform.transform(rb);
1455         rt = layerTransform.transform(rt);
1456     }
1457
1458     if (!s.finalCrop.isEmpty()) {
1459         boundPoint(&lt, s.finalCrop);
1460         boundPoint(&lb, s.finalCrop);
1461         boundPoint(&rb, s.finalCrop);
1462         boundPoint(&rt, s.finalCrop);
1463     }
1464
1465     Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
1466     position[0] = hwTransform.transform(lt);
1467     position[1] = hwTransform.transform(lb);
1468     position[2] = hwTransform.transform(rb);
1469     position[3] = hwTransform.transform(rt);
1470     for (size_t i=0 ; i<4 ; i++) {
1471         position[i].y = hw_h - position[i].y;
1472     }
1473 }
1474
1475 bool Layer::isOpaque(const Layer::State& s) const
1476 {
1477     // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
1478     // layer's opaque flag.
1479     if ((mSidebandStream == nullptr) && (mActiveBuffer == nullptr)) {
1480         return false;
1481     }
1482
1483     // if the layer has the opaque flag, then we're always opaque,
1484     // otherwise we use the current buffer's format.
1485     return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
1486 }
1487
1488 bool Layer::isSecure() const
1489 {
1490     const Layer::State& s(mDrawingState);
1491     return (s.flags & layer_state_t::eLayerSecure);
1492 }
1493
1494 bool Layer::isProtected() const
1495 {
1496     const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
1497     return (activeBuffer != 0) &&
1498             (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1499 }
1500
1501 bool Layer::isFixedSize() const {
1502     return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
1503 }
1504
1505 bool Layer::isCropped() const {
1506     return !mCurrentCrop.isEmpty();
1507 }
1508
1509 bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1510     return mNeedsFiltering || hw->needsFiltering();
1511 }
1512
1513 void Layer::setVisibleRegion(const Region& visibleRegion) {
1514     // always called from main thread
1515     this->visibleRegion = visibleRegion;
1516 }
1517
1518 void Layer::setCoveredRegion(const Region& coveredRegion) {
1519     // always called from main thread
1520     this->coveredRegion = coveredRegion;
1521 }
1522
1523 void Layer::setVisibleNonTransparentRegion(const Region&
1524         setVisibleNonTransparentRegion) {
1525     // always called from main thread
1526     this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1527 }
1528
1529 // ----------------------------------------------------------------------------
1530 // transaction
1531 // ----------------------------------------------------------------------------
1532
1533 void Layer::pushPendingState() {
1534     if (!mCurrentState.modified) {
1535         return;
1536     }
1537
1538     // If this transaction is waiting on the receipt of a frame, generate a sync
1539     // point and send it to the remote layer.
1540     if (mCurrentState.barrierLayer != nullptr) {
1541         sp<Layer> barrierLayer = mCurrentState.barrierLayer.promote();
1542         if (barrierLayer == nullptr) {
1543             ALOGE("[%s] Unable to promote barrier Layer.", mName.string());
1544             // If we can't promote the layer we are intended to wait on,
1545             // then it is expired or otherwise invalid. Allow this transaction
1546             // to be applied as per normal (no synchronization).
1547             mCurrentState.barrierLayer = nullptr;
1548         } else {
1549             auto syncPoint = std::make_shared<SyncPoint>(
1550                     mCurrentState.frameNumber);
1551             if (barrierLayer->addSyncPoint(syncPoint)) {
1552                 mRemoteSyncPoints.push_back(std::move(syncPoint));
1553             } else {
1554                 // We already missed the frame we're supposed to synchronize
1555                 // on, so go ahead and apply the state update
1556                 mCurrentState.barrierLayer = nullptr;
1557             }
1558         }
1559
1560         // Wake us up to check if the frame has been received
1561         setTransactionFlags(eTransactionNeeded);
1562         mFlinger->setTransactionFlags(eTraversalNeeded);
1563     }
1564     mPendingStates.push_back(mCurrentState);
1565     ATRACE_INT(mTransactionName.string(), mPendingStates.size());
1566 }
1567
1568 void Layer::popPendingState(State* stateToCommit) {
1569     auto oldFlags = stateToCommit->flags;
1570     *stateToCommit = mPendingStates[0];
1571     stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1572             (stateToCommit->flags & stateToCommit->mask);
1573
1574     mPendingStates.removeAt(0);
1575     ATRACE_INT(mTransactionName.string(), mPendingStates.size());
1576 }
1577
1578 bool Layer::applyPendingStates(State* stateToCommit) {
1579     bool stateUpdateAvailable = false;
1580     while (!mPendingStates.empty()) {
1581         if (mPendingStates[0].barrierLayer != nullptr) {
1582             if (mRemoteSyncPoints.empty()) {
1583                 // If we don't have a sync point for this, apply it anyway. It
1584                 // will be visually wrong, but it should keep us from getting
1585                 // into too much trouble.
1586                 ALOGE("[%s] No local sync point found", mName.string());
1587                 popPendingState(stateToCommit);
1588                 stateUpdateAvailable = true;
1589                 continue;
1590             }
1591
1592             if (mRemoteSyncPoints.front()->getFrameNumber() !=
1593                     mPendingStates[0].frameNumber) {
1594                 ALOGE("[%s] Unexpected sync point frame number found",
1595                         mName.string());
1596
1597                 // Signal our end of the sync point and then dispose of it
1598                 mRemoteSyncPoints.front()->setTransactionApplied();
1599                 mRemoteSyncPoints.pop_front();
1600                 continue;
1601             }
1602
1603             if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1604                 // Apply the state update
1605                 popPendingState(stateToCommit);
1606                 stateUpdateAvailable = true;
1607
1608                 // Signal our end of the sync point and then dispose of it
1609                 mRemoteSyncPoints.front()->setTransactionApplied();
1610                 mRemoteSyncPoints.pop_front();
1611             } else {
1612                 break;
1613             }
1614         } else {
1615             popPendingState(stateToCommit);
1616             stateUpdateAvailable = true;
1617         }
1618     }
1619
1620     // If we still have pending updates, wake SurfaceFlinger back up and point
1621     // it at this layer so we can process them
1622     if (!mPendingStates.empty()) {
1623         setTransactionFlags(eTransactionNeeded);
1624         mFlinger->setTransactionFlags(eTraversalNeeded);
1625     }
1626
1627     mCurrentState.modified = false;
1628     return stateUpdateAvailable;
1629 }
1630
1631 void Layer::notifyAvailableFrames() {
1632     auto headFrameNumber = getHeadFrameNumber();
1633     bool headFenceSignaled = headFenceHasSignaled();
1634     Mutex::Autolock lock(mLocalSyncPointMutex);
1635     for (auto& point : mLocalSyncPoints) {
1636         if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
1637             point->setFrameAvailable();
1638         }
1639     }
1640 }
1641
1642 uint32_t Layer::doTransaction(uint32_t flags) {
1643     ATRACE_CALL();
1644
1645     pushPendingState();
1646     Layer::State c = getCurrentState();
1647     if (!applyPendingStates(&c)) {
1648         return 0;
1649     }
1650
1651     const Layer::State& s(getDrawingState());
1652
1653     const bool sizeChanged = (c.requested.w != s.requested.w) ||
1654                              (c.requested.h != s.requested.h);
1655
1656     if (sizeChanged) {
1657         // the size changed, we need to ask our client to request a new buffer
1658         ALOGD_IF(DEBUG_RESIZE,
1659                 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
1660                 "  current={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1661                 "            requested={ wh={%4u,%4u} }}\n"
1662                 "  drawing={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1663                 "            requested={ wh={%4u,%4u} }}\n",
1664                 this, getName().string(), mCurrentTransform,
1665                 getEffectiveScalingMode(),
1666                 c.active.w, c.active.h,
1667                 c.crop.left,
1668                 c.crop.top,
1669                 c.crop.right,
1670                 c.crop.bottom,
1671                 c.crop.getWidth(),
1672                 c.crop.getHeight(),
1673                 c.requested.w, c.requested.h,
1674                 s.active.w, s.active.h,
1675                 s.crop.left,
1676                 s.crop.top,
1677                 s.crop.right,
1678                 s.crop.bottom,
1679                 s.crop.getWidth(),
1680                 s.crop.getHeight(),
1681                 s.requested.w, s.requested.h);
1682
1683         // record the new size, form this point on, when the client request
1684         // a buffer, it'll get the new size.
1685         mSurfaceFlingerConsumer->setDefaultBufferSize(
1686                 c.requested.w, c.requested.h);
1687     }
1688
1689     const bool resizePending = (c.requested.w != c.active.w) ||
1690             (c.requested.h != c.active.h);
1691     if (!isFixedSize()) {
1692         if (resizePending && mSidebandStream == NULL) {
1693             // don't let Layer::doTransaction update the drawing state
1694             // if we have a pending resize, unless we are in fixed-size mode.
1695             // the drawing state will be updated only once we receive a buffer
1696             // with the correct size.
1697             //
1698             // in particular, we want to make sure the clip (which is part
1699             // of the geometry state) is latched together with the size but is
1700             // latched immediately when no resizing is involved.
1701             //
1702             // If a sideband stream is attached, however, we want to skip this
1703             // optimization so that transactions aren't missed when a buffer
1704             // never arrives
1705
1706             flags |= eDontUpdateGeometryState;
1707         }
1708     }
1709
1710     // Here we apply various requested geometry states, depending on our
1711     // latching configuration. See Layer.h for a detailed discussion of
1712     // how geometry latching is controlled.
1713     if (!(flags & eDontUpdateGeometryState)) {
1714         Layer::State& editCurrentState(getCurrentState());
1715
1716         // If mFreezeGeometryUpdates is true we are in the setGeometryAppliesWithResize
1717         // mode, which causes attributes which normally latch regardless of scaling mode,
1718         // to be delayed. We copy the requested state to the active state making sure
1719         // to respect these rules (again see Layer.h for a detailed discussion).
1720         //
1721         // There is an awkward asymmetry in the handling of the crop states in the position
1722         // states, as can be seen below. Largely this arises from position and transform
1723         // being stored in the same data structure while having different latching rules.
1724         // b/38182305
1725         //
1726         // Careful that "c" and editCurrentState may not begin as equivalent due to
1727         // applyPendingStates in the presence of deferred transactions.
1728         if (mFreezeGeometryUpdates) {
1729             float tx = c.active.transform.tx();
1730             float ty = c.active.transform.ty();
1731             c.active = c.requested;
1732             c.active.transform.set(tx, ty);
1733             editCurrentState.active = c.active;
1734         } else {
1735             editCurrentState.active = editCurrentState.requested;
1736             c.active = c.requested;
1737         }
1738     }
1739
1740     if (s.active != c.active) {
1741         // invalidate and recompute the visible regions if needed
1742         flags |= Layer::eVisibleRegion;
1743     }
1744
1745     if (c.sequence != s.sequence) {
1746         // invalidate and recompute the visible regions if needed
1747         flags |= eVisibleRegion;
1748         this->contentDirty = true;
1749
1750         // we may use linear filtering, if the matrix scales us
1751         const uint8_t type = c.active.transform.getType();
1752         mNeedsFiltering = (!c.active.transform.preserveRects() ||
1753                 (type >= Transform::SCALE));
1754     }
1755
1756     // If the layer is hidden, signal and clear out all local sync points so
1757     // that transactions for layers depending on this layer's frames becoming
1758     // visible are not blocked
1759     if (c.flags & layer_state_t::eLayerHidden) {
1760         clearSyncPoints();
1761     }
1762
1763     // Commit the transaction
1764     commitTransaction(c);
1765     return flags;
1766 }
1767
1768 void Layer::commitTransaction(const State& stateToCommit) {
1769     mDrawingState = stateToCommit;
1770 }
1771
1772 uint32_t Layer::getTransactionFlags(uint32_t flags) {
1773     return android_atomic_and(~flags, &mTransactionFlags) & flags;
1774 }
1775
1776 uint32_t Layer::setTransactionFlags(uint32_t flags) {
1777     return android_atomic_or(flags, &mTransactionFlags);
1778 }
1779
1780 bool Layer::setPosition(float x, float y, bool immediate) {
1781     if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
1782         return false;
1783     mCurrentState.sequence++;
1784
1785     // We update the requested and active position simultaneously because
1786     // we want to apply the position portion of the transform matrix immediately,
1787     // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
1788     mCurrentState.requested.transform.set(x, y);
1789     if (immediate && !mFreezeGeometryUpdates) {
1790         // Here we directly update the active state
1791         // unlike other setters, because we store it within
1792         // the transform, but use different latching rules.
1793         // b/38182305
1794         mCurrentState.active.transform.set(x, y);
1795     }
1796     mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1797
1798     mCurrentState.modified = true;
1799     setTransactionFlags(eTransactionNeeded);
1800     return true;
1801 }
1802
1803 bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
1804     ssize_t idx = mCurrentChildren.indexOf(childLayer);
1805     if (idx < 0) {
1806         return false;
1807     }
1808     if (childLayer->setLayer(z)) {
1809         mCurrentChildren.removeAt(idx);
1810         mCurrentChildren.add(childLayer);
1811     }
1812     return true;
1813 }
1814
1815 bool Layer::setLayer(int32_t z) {
1816     if (mCurrentState.z == z)
1817         return false;
1818     mCurrentState.sequence++;
1819     mCurrentState.z = z;
1820     mCurrentState.modified = true;
1821
1822     // Discard all relative layering.
1823     if (mCurrentState.zOrderRelativeOf != nullptr) {
1824         sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
1825         if (strongRelative != nullptr) {
1826             strongRelative->removeZOrderRelative(this);
1827         }
1828         mCurrentState.zOrderRelativeOf = nullptr;
1829     }
1830     setTransactionFlags(eTransactionNeeded);
1831     return true;
1832 }
1833
1834 void Layer::removeZOrderRelative(const wp<Layer>& relative) {
1835     mCurrentState.zOrderRelatives.remove(relative);
1836     mCurrentState.sequence++;
1837     mCurrentState.modified = true;
1838     setTransactionFlags(eTransactionNeeded);
1839 }
1840
1841 void Layer::addZOrderRelative(const wp<Layer>& relative) {
1842     mCurrentState.zOrderRelatives.add(relative);
1843     mCurrentState.modified = true;
1844     mCurrentState.sequence++;
1845     setTransactionFlags(eTransactionNeeded);
1846 }
1847
1848 bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t z) {
1849     sp<Handle> handle = static_cast<Handle*>(relativeToHandle.get());
1850     if (handle == nullptr) {
1851         return false;
1852     }
1853     sp<Layer> relative = handle->owner.promote();
1854     if (relative == nullptr) {
1855         return false;
1856     }
1857
1858     mCurrentState.sequence++;
1859     mCurrentState.modified = true;
1860     mCurrentState.z = z;
1861
1862     mCurrentState.zOrderRelativeOf = relative;
1863     relative->addZOrderRelative(this);
1864
1865     setTransactionFlags(eTransactionNeeded);
1866
1867     return true;
1868 }
1869
1870 bool Layer::setSize(uint32_t w, uint32_t h) {
1871     if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1872         return false;
1873     mCurrentState.requested.w = w;
1874     mCurrentState.requested.h = h;
1875     mCurrentState.modified = true;
1876     setTransactionFlags(eTransactionNeeded);
1877     return true;
1878 }
1879 #ifdef USE_HWC2
1880 bool Layer::setAlpha(float alpha) {
1881 #else
1882 bool Layer::setAlpha(uint8_t alpha) {
1883 #endif
1884     if (mCurrentState.alpha == alpha)
1885         return false;
1886     mCurrentState.sequence++;
1887     mCurrentState.alpha = alpha;
1888     mCurrentState.modified = true;
1889     setTransactionFlags(eTransactionNeeded);
1890     return true;
1891 }
1892 bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1893     mCurrentState.sequence++;
1894     mCurrentState.requested.transform.set(
1895             matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
1896     mCurrentState.modified = true;
1897     setTransactionFlags(eTransactionNeeded);
1898     return true;
1899 }
1900 bool Layer::setTransparentRegionHint(const Region& transparent) {
1901     mCurrentState.requestedTransparentRegion = transparent;
1902     mCurrentState.modified = true;
1903     setTransactionFlags(eTransactionNeeded);
1904     return true;
1905 }
1906 bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1907     const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1908     if (mCurrentState.flags == newFlags)
1909         return false;
1910     mCurrentState.sequence++;
1911     mCurrentState.flags = newFlags;
1912     mCurrentState.mask = mask;
1913     mCurrentState.modified = true;
1914     setTransactionFlags(eTransactionNeeded);
1915     return true;
1916 }
1917
1918 bool Layer::setCrop(const Rect& crop, bool immediate) {
1919     if (mCurrentState.requestedCrop == crop)
1920         return false;
1921     mCurrentState.sequence++;
1922     mCurrentState.requestedCrop = crop;
1923     if (immediate && !mFreezeGeometryUpdates) {
1924         mCurrentState.crop = crop;
1925     }
1926     mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1927
1928     mCurrentState.modified = true;
1929     setTransactionFlags(eTransactionNeeded);
1930     return true;
1931 }
1932
1933 bool Layer::setFinalCrop(const Rect& crop, bool immediate) {
1934     if (mCurrentState.requestedFinalCrop == crop)
1935         return false;
1936     mCurrentState.sequence++;
1937     mCurrentState.requestedFinalCrop = crop;
1938     if (immediate && !mFreezeGeometryUpdates) {
1939         mCurrentState.finalCrop = crop;
1940     }
1941     mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1942
1943     mCurrentState.modified = true;
1944     setTransactionFlags(eTransactionNeeded);
1945     return true;
1946 }
1947
1948 bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1949     if (scalingMode == mOverrideScalingMode)
1950         return false;
1951     mOverrideScalingMode = scalingMode;
1952     setTransactionFlags(eTransactionNeeded);
1953     return true;
1954 }
1955
1956 void Layer::setInfo(uint32_t type, uint32_t appId) {
1957   mCurrentState.appId = appId;
1958   mCurrentState.type = type;
1959   mCurrentState.modified = true;
1960   setTransactionFlags(eTransactionNeeded);
1961 }
1962
1963 uint32_t Layer::getEffectiveScalingMode() const {
1964     if (mOverrideScalingMode >= 0) {
1965       return mOverrideScalingMode;
1966     }
1967     return mCurrentScalingMode;
1968 }
1969
1970 bool Layer::setLayerStack(uint32_t layerStack) {
1971     if (mCurrentState.layerStack == layerStack)
1972         return false;
1973     mCurrentState.sequence++;
1974     mCurrentState.layerStack = layerStack;
1975     mCurrentState.modified = true;
1976     setTransactionFlags(eTransactionNeeded);
1977     return true;
1978 }
1979
1980 bool Layer::setDataSpace(android_dataspace dataSpace) {
1981     if (mCurrentState.dataSpace == dataSpace)
1982         return false;
1983     mCurrentState.sequence++;
1984     mCurrentState.dataSpace = dataSpace;
1985     mCurrentState.modified = true;
1986     setTransactionFlags(eTransactionNeeded);
1987     return true;
1988 }
1989
1990 android_dataspace Layer::getDataSpace() const {
1991     return mCurrentState.dataSpace;
1992 }
1993
1994 uint32_t Layer::getLayerStack() const {
1995     auto p = mDrawingParent.promote();
1996     if (p == nullptr) {
1997         return getDrawingState().layerStack;
1998     }
1999     return p->getLayerStack();
2000 }
2001
2002 void Layer::deferTransactionUntil(const sp<Layer>& barrierLayer,
2003         uint64_t frameNumber) {
2004     mCurrentState.barrierLayer = barrierLayer;
2005     mCurrentState.frameNumber = frameNumber;
2006     // We don't set eTransactionNeeded, because just receiving a deferral
2007     // request without any other state updates shouldn't actually induce a delay
2008     mCurrentState.modified = true;
2009     pushPendingState();
2010     mCurrentState.barrierLayer = nullptr;
2011     mCurrentState.frameNumber = 0;
2012     mCurrentState.modified = false;
2013 }
2014
2015 void Layer::deferTransactionUntil(const sp<IBinder>& barrierHandle,
2016         uint64_t frameNumber) {
2017     sp<Handle> handle = static_cast<Handle*>(barrierHandle.get());
2018     deferTransactionUntil(handle->owner.promote(), frameNumber);
2019 }
2020
2021 void Layer::useSurfaceDamage() {
2022     if (mFlinger->mForceFullDamage) {
2023         surfaceDamageRegion = Region::INVALID_REGION;
2024     } else {
2025         surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
2026     }
2027 }
2028
2029 void Layer::useEmptyDamage() {
2030     surfaceDamageRegion.clear();
2031 }
2032
2033 // ----------------------------------------------------------------------------
2034 // pageflip handling...
2035 // ----------------------------------------------------------------------------
2036
2037 bool Layer::shouldPresentNow(const DispSync& dispSync) const {
2038     if (mSidebandStreamChanged || mAutoRefresh) {
2039         return true;
2040     }
2041
2042     Mutex::Autolock lock(mQueueItemLock);
2043     if (mQueueItems.empty()) {
2044         return false;
2045     }
2046     auto timestamp = mQueueItems[0].mTimestamp;
2047     nsecs_t expectedPresent =
2048             mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
2049
2050     // Ignore timestamps more than a second in the future
2051     bool isPlausible = timestamp < (expectedPresent + s2ns(1));
2052     ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
2053             "relative to expectedPresent %" PRId64, mName.string(), timestamp,
2054             expectedPresent);
2055
2056     bool isDue = timestamp < expectedPresent;
2057     return isDue || !isPlausible;
2058 }
2059
2060 bool Layer::onPreComposition(nsecs_t refreshStartTime) {
2061     if (mBufferLatched) {
2062         Mutex::Autolock lock(mFrameEventHistoryMutex);
2063         mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
2064     }
2065     mRefreshPending = false;
2066     return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
2067 }
2068
2069 bool Layer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
2070         const std::shared_ptr<FenceTime>& presentFence,
2071         const CompositorTiming& compositorTiming) {
2072     // mFrameLatencyNeeded is true when a new frame was latched for the
2073     // composition.
2074     if (!mFrameLatencyNeeded)
2075         return false;
2076
2077     // Update mFrameEventHistory.
2078     {
2079         Mutex::Autolock lock(mFrameEventHistoryMutex);
2080         mFrameEventHistory.addPostComposition(mCurrentFrameNumber,
2081                 glDoneFence, presentFence, compositorTiming);
2082     }
2083
2084     // Update mFrameTracker.
2085     nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
2086     mFrameTracker.setDesiredPresentTime(desiredPresentTime);
2087
2088     std::shared_ptr<FenceTime> frameReadyFence =
2089             mSurfaceFlingerConsumer->getCurrentFenceTime();
2090     if (frameReadyFence->isValid()) {
2091         mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
2092     } else {
2093         // There was no fence for this frame, so assume that it was ready
2094         // to be presented at the desired present time.
2095         mFrameTracker.setFrameReadyTime(desiredPresentTime);
2096     }
2097
2098     if (presentFence->isValid()) {
2099         mFrameTracker.setActualPresentFence(
2100                 std::shared_ptr<FenceTime>(presentFence));
2101     } else {
2102         // The HWC doesn't support present fences, so use the refresh
2103         // timestamp instead.
2104         mFrameTracker.setActualPresentTime(
2105             mFlinger->getHwComposer().getRefreshTimestamp(
2106                 HWC_DISPLAY_PRIMARY));
2107     }
2108
2109     mFrameTracker.advanceFrame();
2110     mFrameLatencyNeeded = false;
2111     return true;
2112 }
2113
2114 #ifdef USE_HWC2
2115 void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2116     if (!mSurfaceFlingerConsumer->releasePendingBuffer()) {
2117         return;
2118     }
2119
2120     auto releaseFenceTime = std::make_shared<FenceTime>(
2121             mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
2122     mReleaseTimeline.updateSignalTimes();
2123     mReleaseTimeline.push(releaseFenceTime);
2124
2125     Mutex::Autolock lock(mFrameEventHistoryMutex);
2126     if (mPreviousFrameNumber != 0) {
2127         mFrameEventHistory.addRelease(mPreviousFrameNumber,
2128                 dequeueReadyTime, std::move(releaseFenceTime));
2129     }
2130 }
2131 #endif
2132
2133 bool Layer::isHiddenByPolicy() const {
2134     const Layer::State& s(mDrawingState);
2135     const auto& parent = mDrawingParent.promote();
2136     if (parent != nullptr && parent->isHiddenByPolicy()) {
2137         return true;
2138     }
2139     return s.flags & layer_state_t::eLayerHidden;
2140 }
2141
2142 bool Layer::isVisible() const {
2143 #ifdef USE_HWC2
2144     return !(isHiddenByPolicy()) && getAlpha() > 0.0f
2145             && (mActiveBuffer != NULL || mSidebandStream != NULL);
2146 #else
2147     return !(isHiddenByPolicy()) && getAlpha()
2148             && (mActiveBuffer != NULL || mSidebandStream != NULL);
2149 #endif
2150 }
2151
2152 bool Layer::allTransactionsSignaled() {
2153     auto headFrameNumber = getHeadFrameNumber();
2154     bool matchingFramesFound = false;
2155     bool allTransactionsApplied = true;
2156     Mutex::Autolock lock(mLocalSyncPointMutex);
2157
2158     for (auto& point : mLocalSyncPoints) {
2159         if (point->getFrameNumber() > headFrameNumber) {
2160             break;
2161         }
2162         matchingFramesFound = true;
2163
2164         if (!point->frameIsAvailable()) {
2165            // We haven't notified the remote layer that the frame for
2166            // this point is available yet. Notify it now, and then
2167            // abort this attempt to latch.
2168            point->setFrameAvailable();
2169            allTransactionsApplied = false;
2170            break;
2171         }
2172
2173         allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
2174     }
2175     return !matchingFramesFound || allTransactionsApplied;
2176 }
2177
2178 Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime)
2179 {
2180     ATRACE_CALL();
2181
2182     if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
2183         // mSidebandStreamChanged was true
2184         mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
2185         if (mSidebandStream != NULL) {
2186             setTransactionFlags(eTransactionNeeded);
2187             mFlinger->setTransactionFlags(eTraversalNeeded);
2188         }
2189         recomputeVisibleRegions = true;
2190
2191         const State& s(getDrawingState());
2192         return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
2193     }
2194
2195     Region outDirtyRegion;
2196     if (mQueuedFrames <= 0 && !mAutoRefresh) {
2197         return outDirtyRegion;
2198     }
2199
2200     // if we've already called updateTexImage() without going through
2201     // a composition step, we have to skip this layer at this point
2202     // because we cannot call updateTeximage() without a corresponding
2203     // compositionComplete() call.
2204     // we'll trigger an update in onPreComposition().
2205     if (mRefreshPending) {
2206         return outDirtyRegion;
2207     }
2208
2209     // If the head buffer's acquire fence hasn't signaled yet, return and
2210     // try again later
2211     if (!headFenceHasSignaled()) {
2212         mFlinger->signalLayerUpdate();
2213         return outDirtyRegion;
2214     }
2215
2216     // Capture the old state of the layer for comparisons later
2217     const State& s(getDrawingState());
2218     const bool oldOpacity = isOpaque(s);
2219     sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
2220
2221     if (!allTransactionsSignaled()) {
2222         mFlinger->signalLayerUpdate();
2223         return outDirtyRegion;
2224     }
2225
2226     // This boolean is used to make sure that SurfaceFlinger's shadow copy
2227     // of the buffer queue isn't modified when the buffer queue is returning
2228     // BufferItem's that weren't actually queued. This can happen in shared
2229     // buffer mode.
2230     bool queuedBuffer = false;
2231     LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
2232                     getProducerStickyTransform() != 0, mName.string(),
2233                     mOverrideScalingMode, mFreezeGeometryUpdates);
2234     status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
2235             mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
2236             mLastFrameNumberReceived);
2237     if (updateResult == BufferQueue::PRESENT_LATER) {
2238         // Producer doesn't want buffer to be displayed yet.  Signal a
2239         // layer update so we check again at the next opportunity.
2240         mFlinger->signalLayerUpdate();
2241         return outDirtyRegion;
2242     } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
2243         // If the buffer has been rejected, remove it from the shadow queue
2244         // and return early
2245         if (queuedBuffer) {
2246             Mutex::Autolock lock(mQueueItemLock);
2247             mQueueItems.removeAt(0);
2248             android_atomic_dec(&mQueuedFrames);
2249         }
2250         return outDirtyRegion;
2251     } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2252         // This can occur if something goes wrong when trying to create the
2253         // EGLImage for this buffer. If this happens, the buffer has already
2254         // been released, so we need to clean up the queue and bug out
2255         // early.
2256         if (queuedBuffer) {
2257             Mutex::Autolock lock(mQueueItemLock);
2258             mQueueItems.clear();
2259             android_atomic_and(0, &mQueuedFrames);
2260         }
2261
2262         // Once we have hit this state, the shadow queue may no longer
2263         // correctly reflect the incoming BufferQueue's contents, so even if
2264         // updateTexImage starts working, the only safe course of action is
2265         // to continue to ignore updates.
2266         mUpdateTexImageFailed = true;
2267
2268         return outDirtyRegion;
2269     }
2270
2271     if (queuedBuffer) {
2272         // Autolock scope
2273         auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2274
2275         Mutex::Autolock lock(mQueueItemLock);
2276
2277         // Remove any stale buffers that have been dropped during
2278         // updateTexImage
2279         while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
2280             mQueueItems.removeAt(0);
2281             android_atomic_dec(&mQueuedFrames);
2282         }
2283
2284         mQueueItems.removeAt(0);
2285     }
2286
2287
2288     // Decrement the queued-frames count.  Signal another event if we
2289     // have more frames pending.
2290     if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2291             || mAutoRefresh) {
2292         mFlinger->signalLayerUpdate();
2293     }
2294
2295     // update the active buffer
2296     mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(
2297             &mActiveBufferSlot);
2298     if (mActiveBuffer == NULL) {
2299         // this can only happen if the very first buffer was rejected.
2300         return outDirtyRegion;
2301     }
2302
2303     mBufferLatched = true;
2304     mPreviousFrameNumber = mCurrentFrameNumber;
2305     mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2306
2307     {
2308         Mutex::Autolock lock(mFrameEventHistoryMutex);
2309         mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
2310 #ifndef USE_HWC2
2311         auto releaseFenceTime = std::make_shared<FenceTime>(
2312                 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
2313         mReleaseTimeline.updateSignalTimes();
2314         mReleaseTimeline.push(releaseFenceTime);
2315         if (mPreviousFrameNumber != 0) {
2316             mFrameEventHistory.addRelease(mPreviousFrameNumber,
2317                     latchTime, std::move(releaseFenceTime));
2318         }
2319 #endif
2320     }
2321
2322     mRefreshPending = true;
2323     mFrameLatencyNeeded = true;
2324     if (oldActiveBuffer == NULL) {
2325          // the first time we receive a buffer, we need to trigger a
2326          // geometry invalidation.
2327         recomputeVisibleRegions = true;
2328      }
2329
2330     setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
2331
2332     Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2333     const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2334     const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2335     if ((crop != mCurrentCrop) ||
2336         (transform != mCurrentTransform) ||
2337         (scalingMode != mCurrentScalingMode))
2338     {
2339         mCurrentCrop = crop;
2340         mCurrentTransform = transform;
2341         mCurrentScalingMode = scalingMode;
2342         recomputeVisibleRegions = true;
2343     }
2344
2345     if (oldActiveBuffer != NULL) {
2346         uint32_t bufWidth  = mActiveBuffer->getWidth();
2347         uint32_t bufHeight = mActiveBuffer->getHeight();
2348         if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2349             bufHeight != uint32_t(oldActiveBuffer->height)) {
2350             recomputeVisibleRegions = true;
2351         }
2352     }
2353
2354     mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2355     if (oldOpacity != isOpaque(s)) {
2356         recomputeVisibleRegions = true;
2357     }
2358
2359     // Remove any sync points corresponding to the buffer which was just
2360     // latched
2361     {
2362         Mutex::Autolock lock(mLocalSyncPointMutex);
2363         auto point = mLocalSyncPoints.begin();
2364         while (point != mLocalSyncPoints.end()) {
2365             if (!(*point)->frameIsAvailable() ||
2366                     !(*point)->transactionIsApplied()) {
2367                 // This sync point must have been added since we started
2368                 // latching. Don't drop it yet.
2369                 ++point;
2370                 continue;
2371             }
2372
2373             if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2374                 point = mLocalSyncPoints.erase(point);
2375             } else {
2376                 ++point;
2377             }
2378         }
2379     }
2380
2381     // FIXME: postedRegion should be dirty & bounds
2382     Region dirtyRegion(Rect(s.active.w, s.active.h));
2383
2384     // transform the dirty region to window-manager space
2385     outDirtyRegion = (getTransform().transform(dirtyRegion));
2386
2387     return outDirtyRegion;
2388 }
2389
2390 uint32_t Layer::getEffectiveUsage(uint32_t usage) const
2391 {
2392     // TODO: should we do something special if mSecure is set?
2393     if (mProtectedByApp) {
2394         // need a hardware-protected path to external video sink
2395         usage |= GraphicBuffer::USAGE_PROTECTED;
2396     }
2397     if (mPotentialCursor) {
2398         usage |= GraphicBuffer::USAGE_CURSOR;
2399     }
2400     usage |= GraphicBuffer::USAGE_HW_COMPOSER;
2401     return usage;
2402 }
2403
2404 void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
2405     uint32_t orientation = 0;
2406     if (!mFlinger->mDebugDisableTransformHint) {
2407         // The transform hint is used to improve performance, but we can
2408         // only have a single transform hint, it cannot
2409         // apply to all displays.
2410         const Transform& planeTransform(hw->getTransform());
2411         orientation = planeTransform.getOrientation();
2412         if (orientation & Transform::ROT_INVALID) {
2413             orientation = 0;
2414         }
2415     }
2416     mSurfaceFlingerConsumer->setTransformHint(orientation);
2417 }
2418
2419 // ----------------------------------------------------------------------------
2420 // debugging
2421 // ----------------------------------------------------------------------------
2422
2423 void Layer::dump(String8& result, Colorizer& colorizer) const
2424 {
2425     const Layer::State& s(getDrawingState());
2426
2427     colorizer.colorize(result, Colorizer::GREEN);
2428     result.appendFormat(
2429             "+ %s %p (%s)\n",
2430             getTypeId(), this, getName().string());
2431     colorizer.reset(result);
2432
2433     s.activeTransparentRegion.dump(result, "transparentRegion");
2434     visibleRegion.dump(result, "visibleRegion");
2435     surfaceDamageRegion.dump(result, "surfaceDamageRegion");
2436     sp<Client> client(mClientRef.promote());
2437     PixelFormat pf = PIXEL_FORMAT_UNKNOWN;
2438     const sp<GraphicBuffer>& buffer(getActiveBuffer());
2439     if (buffer != NULL) {
2440         pf = buffer->getPixelFormat();
2441     }
2442
2443     result.appendFormat(            "      "
2444             "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2445             "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
2446             "isOpaque=%1d, invalidate=%1d, "
2447             "dataspace=%s, pixelformat=%s "
2448 #ifdef USE_HWC2
2449             "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2450 #else
2451             "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2452 #endif
2453             "      client=%p\n",
2454             getLayerStack(), s.z,
2455             s.active.transform.tx(), s.active.transform.ty(),
2456             s.active.w, s.active.h,
2457             s.crop.left, s.crop.top,
2458             s.crop.right, s.crop.bottom,
2459             s.finalCrop.left, s.finalCrop.top,
2460             s.finalCrop.right, s.finalCrop.bottom,
2461             isOpaque(s), contentDirty,
2462             dataspaceDetails(getDataSpace()).c_str(), decodePixelFormat(pf).c_str(),
2463             s.alpha, s.flags,
2464             s.active.transform[0][0], s.active.transform[0][1],
2465             s.active.transform[1][0], s.active.transform[1][1],
2466             client.get());
2467
2468     sp<const GraphicBuffer> buf0(mActiveBuffer);
2469     uint32_t w0=0, h0=0, s0=0, f0=0;
2470     if (buf0 != 0) {
2471         w0 = buf0->getWidth();
2472         h0 = buf0->getHeight();
2473         s0 = buf0->getStride();
2474         f0 = buf0->format;
2475     }
2476     result.appendFormat(
2477             "      "
2478             "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2479             " queued-frames=%d, mRefreshPending=%d\n",
2480             mFormat, w0, h0, s0,f0,
2481             mQueuedFrames, mRefreshPending);
2482
2483     if (mSurfaceFlingerConsumer != 0) {
2484         mSurfaceFlingerConsumer->dumpState(result, "            ");
2485     }
2486 }
2487
2488 #ifdef USE_HWC2
2489 void Layer::miniDumpHeader(String8& result) {
2490     result.append("----------------------------------------");
2491     result.append("---------------------------------------\n");
2492     result.append(" Layer name\n");
2493     result.append("           Z | ");
2494     result.append(" Comp Type | ");
2495     result.append("  Disp Frame (LTRB) | ");
2496     result.append("         Source Crop (LTRB)\n");
2497     result.append("----------------------------------------");
2498     result.append("---------------------------------------\n");
2499 }
2500
2501 void Layer::miniDump(String8& result, int32_t hwcId) const {
2502     if (mHwcLayers.count(hwcId) == 0) {
2503         return;
2504     }
2505
2506     String8 name;
2507     if (mName.length() > 77) {
2508         std::string shortened;
2509         shortened.append(mName.string(), 36);
2510         shortened.append("[...]");
2511         shortened.append(mName.string() + (mName.length() - 36), 36);
2512         name = shortened.c_str();
2513     } else {
2514         name = mName;
2515     }
2516
2517     result.appendFormat(" %s\n", name.string());
2518
2519     const Layer::State& layerState(getDrawingState());
2520     const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
2521     result.appendFormat("  %10u | ", layerState.z);
2522     result.appendFormat("%10s | ",
2523             to_string(getCompositionType(hwcId)).c_str());
2524     const Rect& frame = hwcInfo.displayFrame;
2525     result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2526             frame.right, frame.bottom);
2527     const FloatRect& crop = hwcInfo.sourceCrop;
2528     result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2529             crop.right, crop.bottom);
2530
2531     result.append("- - - - - - - - - - - - - - - - - - - - ");
2532     result.append("- - - - - - - - - - - - - - - - - - - -\n");
2533 }
2534 #endif
2535
2536 void Layer::dumpFrameStats(String8& result) const {
2537     mFrameTracker.dumpStats(result);
2538 }
2539
2540 void Layer::clearFrameStats() {
2541     mFrameTracker.clearStats();
2542 }
2543
2544 void Layer::logFrameStats() {
2545     mFrameTracker.logAndResetStats(mName);
2546 }
2547
2548 void Layer::getFrameStats(FrameStats* outStats) const {
2549     mFrameTracker.getStats(outStats);
2550 }
2551
2552 void Layer::dumpFrameEvents(String8& result) {
2553     result.appendFormat("- Layer %s (%s, %p)\n",
2554             getName().string(), getTypeId(), this);
2555     Mutex::Autolock lock(mFrameEventHistoryMutex);
2556     mFrameEventHistory.checkFencesForCompletion();
2557     mFrameEventHistory.dump(result);
2558 }
2559
2560 void Layer::onDisconnect() {
2561     Mutex::Autolock lock(mFrameEventHistoryMutex);
2562     mFrameEventHistory.onDisconnect();
2563 }
2564
2565 void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
2566         FrameEventHistoryDelta *outDelta) {
2567     Mutex::Autolock lock(mFrameEventHistoryMutex);
2568     if (newTimestamps) {
2569         // If there are any unsignaled fences in the aquire timeline at this
2570         // point, the previously queued frame hasn't been latched yet. Go ahead
2571         // and try to get the signal time here so the syscall is taken out of
2572         // the main thread's critical path.
2573         mAcquireTimeline.updateSignalTimes();
2574         // Push the new fence after updating since it's likely still pending.
2575         mAcquireTimeline.push(newTimestamps->acquireFence);
2576         mFrameEventHistory.addQueue(*newTimestamps);
2577     }
2578
2579     if (outDelta) {
2580         mFrameEventHistory.getAndResetDelta(outDelta);
2581     }
2582 }
2583
2584 std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2585         bool forceFlush) {
2586     std::vector<OccupancyTracker::Segment> history;
2587     status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2588             &history);
2589     if (result != NO_ERROR) {
2590         ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2591                 result);
2592         return {};
2593     }
2594     return history;
2595 }
2596
2597 bool Layer::getTransformToDisplayInverse() const {
2598     return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2599 }
2600
2601 size_t Layer::getChildrenCount() const {
2602     size_t count = 0;
2603     for (const sp<Layer>& child : mCurrentChildren) {
2604         count += 1 + child->getChildrenCount();
2605     }
2606     return count;
2607 }
2608
2609 void Layer::addChild(const sp<Layer>& layer) {
2610     mCurrentChildren.add(layer);
2611     layer->setParent(this);
2612 }
2613
2614 ssize_t Layer::removeChild(const sp<Layer>& layer) {
2615     layer->setParent(nullptr);
2616     return mCurrentChildren.remove(layer);
2617 }
2618
2619 bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
2620     sp<Handle> handle = nullptr;
2621     sp<Layer> newParent = nullptr;
2622     if (newParentHandle == nullptr) {
2623         return false;
2624     }
2625     handle = static_cast<Handle*>(newParentHandle.get());
2626     newParent = handle->owner.promote();
2627     if (newParent == nullptr) {
2628         ALOGE("Unable to promote Layer handle");
2629         return false;
2630     }
2631
2632     for (const sp<Layer>& child : mCurrentChildren) {
2633         newParent->addChild(child);
2634
2635         sp<Client> client(child->mClientRef.promote());
2636         if (client != nullptr) {
2637             client->setParentLayer(newParent);
2638         }
2639     }
2640     mCurrentChildren.clear();
2641
2642     return true;
2643 }
2644
2645 bool Layer::detachChildren() {
2646     traverseInZOrder(LayerVector::StateSet::Drawing, [this](Layer* child) {
2647         if (child == this) {
2648             return;
2649         }
2650
2651         sp<Client> client(child->mClientRef.promote());
2652         if (client != nullptr) {
2653             client->detachLayer(child);
2654         }
2655     });
2656
2657     return true;
2658 }
2659
2660 void Layer::setParent(const sp<Layer>& layer) {
2661     mCurrentParent = layer;
2662 }
2663
2664 void Layer::clearSyncPoints() {
2665     for (const auto& child : mCurrentChildren) {
2666         child->clearSyncPoints();
2667     }
2668
2669     Mutex::Autolock lock(mLocalSyncPointMutex);
2670     for (auto& point : mLocalSyncPoints) {
2671         point->setFrameAvailable();
2672     }
2673     mLocalSyncPoints.clear();
2674 }
2675
2676 int32_t Layer::getZ() const {
2677     return mDrawingState.z;
2678 }
2679
2680 LayerVector Layer::makeTraversalList(LayerVector::StateSet stateSet) {
2681     LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2682                         "makeTraversalList received invalid stateSet");
2683     const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2684     const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2685     const State& state = useDrawing ? mDrawingState : mCurrentState;
2686
2687     if (state.zOrderRelatives.size() == 0) {
2688         return children;
2689     }
2690     LayerVector traverse;
2691
2692     for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2693         sp<Layer> strongRelative = weakRelative.promote();
2694         if (strongRelative != nullptr) {
2695             traverse.add(strongRelative);
2696         }
2697     }
2698
2699     for (const sp<Layer>& child : children) {
2700         traverse.add(child);
2701     }
2702
2703     return traverse;
2704 }
2705
2706 /**
2707  * Negatively signed relatives are before 'this' in Z-order.
2708  */
2709 void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
2710     LayerVector list = makeTraversalList(stateSet);
2711
2712     size_t i = 0;
2713     for (; i < list.size(); i++) {
2714         const auto& relative = list[i];
2715         if (relative->getZ() >= 0) {
2716             break;
2717         }
2718         relative->traverseInZOrder(stateSet, visitor);
2719     }
2720     visitor(this);
2721     for (; i < list.size(); i++) {
2722         const auto& relative = list[i];
2723         relative->traverseInZOrder(stateSet, visitor);
2724     }
2725 }
2726
2727 /**
2728  * Positively signed relatives are before 'this' in reverse Z-order.
2729  */
2730 void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
2731                                     const LayerVector::Visitor& visitor) {
2732     LayerVector list = makeTraversalList(stateSet);
2733
2734     int32_t i = 0;
2735     for (i = list.size()-1; i>=0; i--) {
2736         const auto& relative = list[i];
2737         if (relative->getZ() < 0) {
2738             break;
2739         }
2740         relative->traverseInReverseZOrder(stateSet, visitor);
2741     }
2742     visitor(this);
2743     for (; i>=0; i--) {
2744         const auto& relative = list[i];
2745         relative->traverseInReverseZOrder(stateSet, visitor);
2746     }
2747 }
2748
2749 Transform Layer::getTransform() const {
2750     Transform t;
2751     const auto& p = mDrawingParent.promote();
2752     if (p != nullptr) {
2753         t = p->getTransform();
2754
2755         // If the parent is not using NATIVE_WINDOW_SCALING_MODE_FREEZE (e.g.
2756         // it isFixedSize) then there may be additional scaling not accounted
2757         // for in the transform. We need to mirror this scaling in child surfaces
2758         // or we will break the contract where WM can treat child surfaces as
2759         // pixels in the parent surface.
2760         if (p->isFixedSize() && p->mActiveBuffer != nullptr) {
2761             int bufferWidth;
2762             int bufferHeight;
2763             if ((p->mCurrentTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) == 0) {
2764                 bufferWidth = p->mActiveBuffer->getWidth();
2765                 bufferHeight = p->mActiveBuffer->getHeight();
2766             } else {
2767                 bufferHeight = p->mActiveBuffer->getWidth();
2768                 bufferWidth = p->mActiveBuffer->getHeight();
2769             }
2770             float sx = p->getDrawingState().active.w /
2771                     static_cast<float>(bufferWidth);
2772             float sy = p->getDrawingState().active.h /
2773                     static_cast<float>(bufferHeight);
2774             Transform extraParentScaling;
2775             extraParentScaling.set(sx, 0, 0, sy);
2776             t = t * extraParentScaling;
2777         }
2778     }
2779     return t * getDrawingState().active.transform;
2780 }
2781
2782 #ifdef USE_HWC2
2783 float Layer::getAlpha() const {
2784     const auto& p = mDrawingParent.promote();
2785
2786     float parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0;
2787     return parentAlpha * getDrawingState().alpha;
2788 }
2789 #else
2790 uint8_t Layer::getAlpha() const {
2791     const auto& p = mDrawingParent.promote();
2792
2793     float parentAlpha = (p != nullptr) ? (p->getAlpha() / 255.0f) : 1.0;
2794     float drawingAlpha = getDrawingState().alpha / 255.0f;
2795     drawingAlpha = drawingAlpha * parentAlpha;
2796     return static_cast<uint8_t>(std::round(drawingAlpha * 255));
2797 }
2798 #endif
2799
2800 void Layer::commitChildList() {
2801     for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2802         const auto& child = mCurrentChildren[i];
2803         child->commitChildList();
2804     }
2805     mDrawingChildren = mCurrentChildren;
2806     mDrawingParent = mCurrentParent;
2807 }
2808
2809 // ---------------------------------------------------------------------------
2810
2811 }; // namespace android
2812
2813 #if defined(__gl_h_)
2814 #error "don't include gl/gl.h in this file"
2815 #endif
2816
2817 #if defined(__gl2_h_)
2818 #error "don't include gl2/gl2.h in this file"
2819 #endif