OSDN Git Service

sf : Fix vertices & texture coordinates computation.
[android-x86/frameworks-native.git] / services / surfaceflinger / Layer.cpp
1 /*
2  * Copyright (c) 2016, The Linux Foundation. All rights reserved.
3  * Not a Contribution
4  *
5  *
6  * Copyright (C) 2007 The Android Open Source Project
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  */
20
21 //#define LOG_NDEBUG 0
22 #undef LOG_TAG
23 #define LOG_TAG "Layer"
24 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
25
26 #include <stdlib.h>
27 #include <stdint.h>
28 #include <sys/types.h>
29 #include <math.h>
30
31 #include <cutils/compiler.h>
32 #include <cutils/native_handle.h>
33 #include <cutils/properties.h>
34
35 #include <utils/Errors.h>
36 #include <utils/Log.h>
37 #include <utils/NativeHandle.h>
38 #include <utils/StopWatch.h>
39 #include <utils/Trace.h>
40
41 #include <ui/GraphicBuffer.h>
42 #include <ui/PixelFormat.h>
43
44 #include <gui/BufferItem.h>
45 #include <gui/Surface.h>
46
47 #include "clz.h"
48 #include "Colorizer.h"
49 #include "DisplayDevice.h"
50 #include "Layer.h"
51 #include "MonitoredProducer.h"
52 #include "SurfaceFlinger.h"
53
54 #include "DisplayHardware/HWComposer.h"
55
56 #include "RenderEngine/RenderEngine.h"
57
58 #define DEBUG_RESIZE    0
59
60 namespace android {
61
62 // ---------------------------------------------------------------------------
63
64 int32_t Layer::sSequence = 1;
65
66 Layer::Layer(SurfaceFlinger* flinger, const sp<Client>& client,
67         const String8& name, uint32_t w, uint32_t h, uint32_t flags)
68     :   contentDirty(false),
69         sequence(uint32_t(android_atomic_inc(&sSequence))),
70         mFlinger(flinger),
71         mTextureName(-1U),
72         mPremultipliedAlpha(true),
73         mName("unnamed"),
74         mFormat(PIXEL_FORMAT_NONE),
75         mTransactionFlags(0),
76         mPendingStateMutex(),
77         mPendingStates(),
78         mQueuedFrames(0),
79         mSidebandStreamChanged(false),
80         mCurrentTransform(0),
81         mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
82         mOverrideScalingMode(-1),
83         mCurrentOpacity(true),
84         mCurrentFrameNumber(0),
85         mRefreshPending(false),
86         mFrameLatencyNeeded(false),
87         mFiltering(false),
88         mNeedsFiltering(false),
89         mMesh(Mesh::TRIANGLE_FAN, 4, 2, 2),
90 #ifndef USE_HWC2
91         mIsGlesComposition(false),
92 #endif
93         mProtectedByApp(false),
94         mHasSurface(false),
95         mClientRef(client),
96         mPotentialCursor(false),
97         mQueueItemLock(),
98         mQueueItemCondition(),
99         mQueueItems(),
100         mLastFrameNumberReceived(0),
101         mUpdateTexImageFailed(false),
102         mAutoRefresh(false),
103         mFreezePositionUpdates(false),
104         mTransformHint(0)
105 {
106 #ifdef USE_HWC2
107     ALOGV("Creating Layer %s", name.string());
108 #endif
109
110     mCurrentCrop.makeInvalid();
111     mFlinger->getRenderEngine().genTextures(1, &mTextureName);
112     mTexture.init(Texture::TEXTURE_EXTERNAL, mTextureName);
113
114     uint32_t layerFlags = 0;
115     if (flags & ISurfaceComposerClient::eHidden)
116         layerFlags |= layer_state_t::eLayerHidden;
117     if (flags & ISurfaceComposerClient::eOpaque)
118         layerFlags |= layer_state_t::eLayerOpaque;
119     if (flags & ISurfaceComposerClient::eSecure)
120         layerFlags |= layer_state_t::eLayerSecure;
121
122     if (flags & ISurfaceComposerClient::eNonPremultiplied)
123         mPremultipliedAlpha = false;
124
125     mName = name;
126
127     mCurrentState.active.w = w;
128     mCurrentState.active.h = h;
129     mCurrentState.active.transform.set(0, 0);
130     mCurrentState.crop.makeInvalid();
131     mCurrentState.finalCrop.makeInvalid();
132     mCurrentState.z = 0;
133 #ifdef USE_HWC2
134     mCurrentState.alpha = 1.0f;
135 #else
136     mCurrentState.alpha = 0xFF;
137 #endif
138     mCurrentState.layerStack = 0;
139     mCurrentState.flags = layerFlags;
140     mCurrentState.sequence = 0;
141     mCurrentState.requested = mCurrentState.active;
142     mCurrentState.color = 0;
143
144     // drawing state & current state are identical
145     mDrawingState = mCurrentState;
146
147 #ifdef USE_HWC2
148     const auto& hwc = flinger->getHwComposer();
149     const auto& activeConfig = hwc.getActiveConfig(HWC_DISPLAY_PRIMARY);
150     nsecs_t displayPeriod = activeConfig->getVsyncPeriod();
151 #else
152     nsecs_t displayPeriod =
153             flinger->getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
154 #endif
155     mFrameTracker.setDisplayRefreshPeriod(displayPeriod);
156 }
157
158 void Layer::onFirstRef() {
159     // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
160     sp<IGraphicBufferProducer> producer;
161     sp<IGraphicBufferConsumer> consumer;
162     BufferQueue::createBufferQueue(&producer, &consumer);
163     mProducer = new MonitoredProducer(producer, mFlinger);
164     mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName);
165     mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
166     mSurfaceFlingerConsumer->setContentsChangedListener(this);
167     mSurfaceFlingerConsumer->setName(mName);
168
169 #ifdef TARGET_DISABLE_TRIPLE_BUFFERING
170 #warning "disabling triple buffering"
171 #else
172     mProducer->setMaxDequeuedBufferCount(2);
173 #endif
174
175     const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
176     updateTransformHint(hw);
177 }
178
179 Layer::~Layer() {
180   sp<Client> c(mClientRef.promote());
181     if (c != 0) {
182         c->detachLayer(this);
183     }
184
185     for (auto& point : mRemoteSyncPoints) {
186         point->setTransactionApplied();
187     }
188     for (auto& point : mLocalSyncPoints) {
189         point->setFrameAvailable();
190     }
191     mFlinger->deleteTextureAsync(mTextureName);
192     mFrameTracker.logAndResetStats(mName);
193 }
194
195 // ---------------------------------------------------------------------------
196 // callbacks
197 // ---------------------------------------------------------------------------
198
199 #ifdef USE_HWC2
200 void Layer::onLayerDisplayed(const sp<Fence>& releaseFence) {
201     if (mHwcLayers.empty()) {
202         return;
203     }
204     mSurfaceFlingerConsumer->setReleaseFence(releaseFence);
205 }
206 #else
207 void Layer::onLayerDisplayed(const sp<const DisplayDevice>& /* hw */,
208         HWComposer::HWCLayerInterface* layer) {
209     if (layer) {
210         layer->onDisplayed();
211         mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence());
212     }
213 }
214 #endif
215
216 void Layer::onFrameAvailable(const BufferItem& item) {
217     // Add this buffer from our internal queue tracker
218     { // Autolock scope
219         Mutex::Autolock lock(mQueueItemLock);
220
221         // Reset the frame number tracker when we receive the first buffer after
222         // a frame number reset
223         if (item.mFrameNumber == 1) {
224             mLastFrameNumberReceived = 0;
225         }
226
227         // Ensure that callbacks are handled in order
228         while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
229             status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
230                     ms2ns(500));
231             if (result != NO_ERROR) {
232                 ALOGE("[%s] Timed out waiting on callback", mName.string());
233             }
234         }
235
236         mQueueItems.push_back(item);
237         android_atomic_inc(&mQueuedFrames);
238
239         // Wake up any pending callbacks
240         mLastFrameNumberReceived = item.mFrameNumber;
241         mQueueItemCondition.broadcast();
242     }
243
244     mFlinger->signalLayerUpdate();
245 }
246
247 void Layer::onFrameReplaced(const BufferItem& item) {
248     { // Autolock scope
249         Mutex::Autolock lock(mQueueItemLock);
250
251         // Ensure that callbacks are handled in order
252         while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
253             status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
254                     ms2ns(500));
255             if (result != NO_ERROR) {
256                 ALOGE("[%s] Timed out waiting on callback", mName.string());
257             }
258         }
259
260         if (mQueueItems.empty()) {
261             ALOGE("Can't replace a frame on an empty queue");
262             return;
263         }
264         mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
265
266         // Wake up any pending callbacks
267         mLastFrameNumberReceived = item.mFrameNumber;
268         mQueueItemCondition.broadcast();
269     }
270 }
271
272 void Layer::onSidebandStreamChanged() {
273     if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
274         // mSidebandStreamChanged was false
275         mFlinger->signalLayerUpdate();
276     }
277 }
278
279 // called with SurfaceFlinger::mStateLock from the drawing thread after
280 // the layer has been remove from the current state list (and just before
281 // it's removed from the drawing state list)
282 void Layer::onRemoved() {
283     mSurfaceFlingerConsumer->abandon();
284 }
285
286 // ---------------------------------------------------------------------------
287 // set-up
288 // ---------------------------------------------------------------------------
289
290 const String8& Layer::getName() const {
291     return mName;
292 }
293
294 status_t Layer::setBuffers( uint32_t w, uint32_t h,
295                             PixelFormat format, uint32_t flags)
296 {
297     uint32_t const maxSurfaceDims = min(
298             mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
299
300     // never allow a surface larger than what our underlying GL implementation
301     // can handle.
302     if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
303         ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
304         return BAD_VALUE;
305     }
306
307     mFormat = format;
308
309     mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
310     mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
311     mCurrentOpacity = getOpacityForFormat(format);
312
313     mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
314     mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
315     mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
316
317     return NO_ERROR;
318 }
319
320 /*
321  * The layer handle is just a BBinder object passed to the client
322  * (remote process) -- we don't keep any reference on our side such that
323  * the dtor is called when the remote side let go of its reference.
324  *
325  * LayerCleaner ensures that mFlinger->onLayerDestroyed() is called for
326  * this layer when the handle is destroyed.
327  */
328 class Layer::Handle : public BBinder, public LayerCleaner {
329     public:
330         Handle(const sp<SurfaceFlinger>& flinger, const sp<Layer>& layer)
331             : LayerCleaner(flinger, layer), owner(layer) {}
332
333         wp<Layer> owner;
334 };
335
336 sp<IBinder> Layer::getHandle() {
337     Mutex::Autolock _l(mLock);
338
339     LOG_ALWAYS_FATAL_IF(mHasSurface,
340             "Layer::getHandle() has already been called");
341
342     mHasSurface = true;
343
344     return new Handle(mFlinger, this);
345 }
346
347 sp<IGraphicBufferProducer> Layer::getProducer() const {
348     return mProducer;
349 }
350
351 // ---------------------------------------------------------------------------
352 // h/w composer set-up
353 // ---------------------------------------------------------------------------
354
355 Rect Layer::getContentCrop() const {
356     // this is the crop rectangle that applies to the buffer
357     // itself (as opposed to the window)
358     Rect crop;
359     if (!mCurrentCrop.isEmpty()) {
360         // if the buffer crop is defined, we use that
361         crop = mCurrentCrop;
362     } else if (mActiveBuffer != NULL) {
363         // otherwise we use the whole buffer
364         crop = mActiveBuffer->getBounds();
365     } else {
366         // if we don't have a buffer yet, we use an empty/invalid crop
367         crop.makeInvalid();
368     }
369     return crop;
370 }
371
372 Rect Layer::reduce(const Rect& win, const Region& exclude) const{
373     if (CC_LIKELY(exclude.isEmpty())) {
374         return win;
375     }
376     if (exclude.isRect()) {
377         return win.reduce(exclude.getBounds());
378     }
379     return Region(win).subtract(exclude).getBounds();
380 }
381
382 Rect Layer::computeBounds() const {
383     const Layer::State& s(getDrawingState());
384     return computeBounds(s.activeTransparentRegion);
385 }
386
387 Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
388     const Layer::State& s(getDrawingState());
389     Rect win(s.active.w, s.active.h);
390
391     if (!s.crop.isEmpty()) {
392         win.intersect(s.crop, &win);
393     }
394     // subtract the transparent region and snap to the bounds
395     return reduce(win, activeTransparentRegion);
396 }
397
398 FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
399     // the content crop is the area of the content that gets scaled to the
400     // layer's size.
401     FloatRect crop(getContentCrop());
402
403     // the crop is the area of the window that gets cropped, but not
404     // scaled in any ways.
405     const State& s(getDrawingState());
406
407     // apply the projection's clipping to the window crop in
408     // layerstack space, and convert-back to layer space.
409     // if there are no window scaling involved, this operation will map to full
410     // pixels in the buffer.
411     // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
412     // a viewport clipping and a window transform. we should use floating point to fix this.
413
414     Rect activeCrop(s.active.w, s.active.h);
415     if (!s.crop.isEmpty()) {
416         activeCrop = s.crop;
417     }
418
419     activeCrop = s.active.transform.transform(activeCrop);
420     if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
421         activeCrop.clear();
422     }
423     if (!s.finalCrop.isEmpty()) {
424         if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
425             activeCrop.clear();
426         }
427     }
428     activeCrop = s.active.transform.inverse().transform(activeCrop);
429
430     // This needs to be here as transform.transform(Rect) computes the
431     // transformed rect and then takes the bounding box of the result before
432     // returning. This means
433     // transform.inverse().transform(transform.transform(Rect)) != Rect
434     // in which case we need to make sure the final rect is clipped to the
435     // display bounds.
436     if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
437         activeCrop.clear();
438     }
439
440     // subtract the transparent region and snap to the bounds
441     activeCrop = reduce(activeCrop, s.activeTransparentRegion);
442
443     // Transform the window crop to match the buffer coordinate system,
444     // which means using the inverse of the current transform set on the
445     // SurfaceFlingerConsumer.
446     uint32_t invTransform = mCurrentTransform;
447     if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
448         /*
449          * the code below applies the primary display's inverse transform to the
450          * buffer
451          */
452         uint32_t invTransformOrient =
453                 DisplayDevice::getPrimaryDisplayOrientationTransform();
454         // calculate the inverse transform
455         if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
456             invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
457                     NATIVE_WINDOW_TRANSFORM_FLIP_H;
458         }
459         // and apply to the current transform
460         invTransform = (Transform(invTransformOrient) * Transform(invTransform))
461                 .getOrientation();
462     }
463
464     int winWidth = s.active.w;
465     int winHeight = s.active.h;
466     if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
467         // If the activeCrop has been rotate the ends are rotated but not
468         // the space itself so when transforming ends back we can't rely on
469         // a modification of the axes of rotation. To account for this we
470         // need to reorient the inverse rotation in terms of the current
471         // axes of rotation.
472         bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
473         bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
474         if (is_h_flipped == is_v_flipped) {
475             invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
476                     NATIVE_WINDOW_TRANSFORM_FLIP_H;
477         }
478         winWidth = s.active.h;
479         winHeight = s.active.w;
480     }
481     const Rect winCrop = activeCrop.transform(
482             invTransform, s.active.w, s.active.h);
483
484     // below, crop is intersected with winCrop expressed in crop's coordinate space
485     float xScale = crop.getWidth()  / float(winWidth);
486     float yScale = crop.getHeight() / float(winHeight);
487
488     float insetL = winCrop.left                 * xScale;
489     float insetT = winCrop.top                  * yScale;
490     float insetR = (winWidth - winCrop.right )  * xScale;
491     float insetB = (winHeight - winCrop.bottom) * yScale;
492
493     crop.left   += insetL;
494     crop.top    += insetT;
495     crop.right  -= insetR;
496     crop.bottom -= insetB;
497
498     return crop;
499 }
500
501 #ifdef USE_HWC2
502 void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice)
503 #else
504 void Layer::setGeometry(
505     const sp<const DisplayDevice>& hw,
506         HWComposer::HWCLayerInterface& layer)
507 #endif
508 {
509 #ifdef USE_HWC2
510     const auto hwcId = displayDevice->getHwcDisplayId();
511     auto& hwcInfo = mHwcLayers[hwcId];
512 #else
513     layer.setDefaultState();
514 #endif
515
516     // enable this layer
517 #ifdef USE_HWC2
518     hwcInfo.forceClientComposition = false;
519
520     if (isSecure() && !displayDevice->isSecure()) {
521         hwcInfo.forceClientComposition = true;
522     }
523
524     auto& hwcLayer = hwcInfo.layer;
525 #else
526     layer.setSkip(false);
527
528     if (isSecure() && !hw->isSecure()) {
529         layer.setSkip(true);
530     }
531 #endif
532
533     // this gives us only the "orientation" component of the transform
534     const State& s(getDrawingState());
535 #ifdef USE_HWC2
536     if (!isOpaque(s) || s.alpha != 1.0f) {
537         auto blendMode = mPremultipliedAlpha ?
538                 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
539         auto error = hwcLayer->setBlendMode(blendMode);
540         ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
541                 " %s (%d)", mName.string(), to_string(blendMode).c_str(),
542                 to_string(error).c_str(), static_cast<int32_t>(error));
543     }
544 #else
545     if (!isOpaque(s)) {
546         layer.setBlending(mPremultipliedAlpha ?
547                 HWC_BLENDING_PREMULT :
548                 HWC_BLENDING_COVERAGE);
549     }
550 #endif
551
552     // apply the layer's transform, followed by the display's global transform
553     // here we're guaranteed that the layer's transform preserves rects
554     Region activeTransparentRegion(s.activeTransparentRegion);
555     if (!s.crop.isEmpty()) {
556         Rect activeCrop(s.crop);
557         activeCrop = s.active.transform.transform(activeCrop);
558 #ifdef USE_HWC2
559         if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
560 #else
561         if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
562 #endif
563             activeCrop.clear();
564         }
565         activeCrop = s.active.transform.inverse().transform(activeCrop);
566         // This needs to be here as transform.transform(Rect) computes the
567         // transformed rect and then takes the bounding box of the result before
568         // returning. This means
569         // transform.inverse().transform(transform.transform(Rect)) != Rect
570         // in which case we need to make sure the final rect is clipped to the
571         // display bounds.
572         if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
573             activeCrop.clear();
574         }
575         // mark regions outside the crop as transparent
576         activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
577         activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
578                 s.active.w, s.active.h));
579         activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
580                 activeCrop.left, activeCrop.bottom));
581         activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
582                 s.active.w, activeCrop.bottom));
583     }
584     Rect frame(s.active.transform.transform(computeBounds(activeTransparentRegion)));
585     if (!s.finalCrop.isEmpty()) {
586         if(!frame.intersect(s.finalCrop, &frame)) {
587             frame.clear();
588         }
589     }
590 #ifdef USE_HWC2
591     if (!frame.intersect(displayDevice->getViewport(), &frame)) {
592         frame.clear();
593     }
594     const Transform& tr(displayDevice->getTransform());
595     Rect transformedFrame = tr.transform(frame);
596     auto error = hwcLayer->setDisplayFrame(transformedFrame);
597     ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set display frame "
598             "[%d, %d, %d, %d]: %s (%d)", mName.string(), transformedFrame.left,
599             transformedFrame.top, transformedFrame.right,
600             transformedFrame.bottom, to_string(error).c_str(),
601             static_cast<int32_t>(error));
602
603     FloatRect sourceCrop = computeCrop(displayDevice);
604     error = hwcLayer->setSourceCrop(sourceCrop);
605     ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set source crop "
606             "[%.3f, %.3f, %.3f, %.3f]: %s (%d)", mName.string(),
607             sourceCrop.left, sourceCrop.top, sourceCrop.right,
608             sourceCrop.bottom, to_string(error).c_str(),
609             static_cast<int32_t>(error));
610
611     error = hwcLayer->setPlaneAlpha(s.alpha);
612     ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
613             "%s (%d)", mName.string(), s.alpha, to_string(error).c_str(),
614             static_cast<int32_t>(error));
615
616     error = hwcLayer->setZOrder(s.z);
617     ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
618             mName.string(), s.z, to_string(error).c_str(),
619             static_cast<int32_t>(error));
620 #else
621     if (!frame.intersect(hw->getViewport(), &frame)) {
622         frame.clear();
623     }
624     const Transform& tr(hw->getTransform());
625     layer.setFrame(tr.transform(frame));
626     setPosition(hw, layer, s);
627     layer.setCrop(computeCrop(hw));
628     layer.setPlaneAlpha(s.alpha);
629 #endif
630
631     /*
632      * Transformations are applied in this order:
633      * 1) buffer orientation/flip/mirror
634      * 2) state transformation (window manager)
635      * 3) layer orientation (screen orientation)
636      * (NOTE: the matrices are multiplied in reverse order)
637      */
638
639     const Transform bufferOrientation(mCurrentTransform);
640     Transform transform(tr * s.active.transform * bufferOrientation);
641
642     if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
643         /*
644          * the code below applies the primary display's inverse transform to the
645          * buffer
646          */
647         uint32_t invTransform =
648                 DisplayDevice::getPrimaryDisplayOrientationTransform();
649         // calculate the inverse transform
650         if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
651             invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
652                     NATIVE_WINDOW_TRANSFORM_FLIP_H;
653         }
654         // and apply to the current transform
655         transform = Transform(invTransform) * transform;
656     }
657
658     // this gives us only the "orientation" component of the transform
659     const uint32_t orientation = transform.getOrientation();
660 #ifdef USE_HWC2
661     if (orientation & Transform::ROT_INVALID) {
662         // we can only handle simple transformation
663         hwcInfo.forceClientComposition = true;
664     } else {
665         auto transform = static_cast<HWC2::Transform>(orientation);
666         auto error = hwcLayer->setTransform(transform);
667         ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
668                 "%s (%d)", mName.string(), to_string(transform).c_str(),
669                 to_string(error).c_str(), static_cast<int32_t>(error));
670     }
671 #else
672     if (orientation & Transform::ROT_INVALID) {
673         // we can only handle simple transformation
674         layer.setSkip(true);
675     } else {
676         layer.setTransform(orientation);
677     }
678 #endif
679 }
680
681 #ifdef USE_HWC2
682 void Layer::forceClientComposition(int32_t hwcId) {
683     if (mHwcLayers.count(hwcId) == 0) {
684         ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
685         return;
686     }
687
688     mHwcLayers[hwcId].forceClientComposition = true;
689 }
690 #endif
691
692 #ifdef USE_HWC2
693 void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
694     // Apply this display's projection's viewport to the visible region
695     // before giving it to the HWC HAL.
696     const Transform& tr = displayDevice->getTransform();
697     const auto& viewport = displayDevice->getViewport();
698     Region visible = tr.transform(visibleRegion.intersect(viewport));
699     auto hwcId = displayDevice->getHwcDisplayId();
700     auto& hwcLayer = mHwcLayers[hwcId].layer;
701     auto error = hwcLayer->setVisibleRegion(visible);
702     if (error != HWC2::Error::None) {
703         ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
704                 to_string(error).c_str(), static_cast<int32_t>(error));
705         visible.dump(LOG_TAG);
706     }
707
708     error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
709     if (error != HWC2::Error::None) {
710         ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
711                 to_string(error).c_str(), static_cast<int32_t>(error));
712         surfaceDamageRegion.dump(LOG_TAG);
713     }
714
715     // Sideband layers
716     if (mSidebandStream.get()) {
717         setCompositionType(hwcId, HWC2::Composition::Sideband);
718         ALOGV("[%s] Requesting Sideband composition", mName.string());
719         error = hwcLayer->setSidebandStream(mSidebandStream->handle());
720         if (error != HWC2::Error::None) {
721             ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
722                     mName.string(), mSidebandStream->handle(),
723                     to_string(error).c_str(), static_cast<int32_t>(error));
724         }
725         return;
726     }
727
728     // Client or SolidColor layers
729     if (mActiveBuffer == nullptr || mActiveBuffer->handle == nullptr ||
730             mHwcLayers[hwcId].forceClientComposition) {
731         // TODO: This also includes solid color layers, but no API exists to
732         // setup a solid color layer yet
733         ALOGV("[%s] Requesting Client composition", mName.string());
734         setCompositionType(hwcId, HWC2::Composition::Client);
735         error = hwcLayer->setBuffer(nullptr, Fence::NO_FENCE);
736         if (error != HWC2::Error::None) {
737             ALOGE("[%s] Failed to set null buffer: %s (%d)", mName.string(),
738                     to_string(error).c_str(), static_cast<int32_t>(error));
739         }
740         return;
741     }
742
743     // Device or Cursor layers
744     if (mPotentialCursor) {
745         ALOGV("[%s] Requesting Cursor composition", mName.string());
746         setCompositionType(hwcId, HWC2::Composition::Cursor);
747     } else {
748         ALOGV("[%s] Requesting Device composition", mName.string());
749         setCompositionType(hwcId, HWC2::Composition::Device);
750     }
751
752     auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
753     error = hwcLayer->setBuffer(mActiveBuffer->handle, acquireFence);
754     if (error != HWC2::Error::None) {
755         ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
756                 mActiveBuffer->handle, to_string(error).c_str(),
757                 static_cast<int32_t>(error));
758     }
759 }
760 #else
761 void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
762         HWComposer::HWCLayerInterface& layer) {
763     // we have to set the visible region on every frame because
764     // we currently free it during onLayerDisplayed(), which is called
765     // after HWComposer::commit() -- every frame.
766     // Apply this display's projection's viewport to the visible region
767     // before giving it to the HWC HAL.
768     const Transform& tr = hw->getTransform();
769     Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
770     layer.setVisibleRegionScreen(visible);
771     layer.setSurfaceDamage(surfaceDamageRegion);
772     mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
773
774     if (mSidebandStream.get()) {
775         layer.setSidebandStream(mSidebandStream);
776     } else {
777         // NOTE: buffer can be NULL if the client never drew into this
778         // layer yet, or if we ran out of memory
779         layer.setBuffer(mActiveBuffer);
780     }
781 }
782 #endif
783
784 #ifdef USE_HWC2
785 void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
786     auto hwcId = displayDevice->getHwcDisplayId();
787     if (mHwcLayers.count(hwcId) == 0 ||
788             getCompositionType(hwcId) != HWC2::Composition::Cursor) {
789         return;
790     }
791
792     // This gives us only the "orientation" component of the transform
793     const State& s(getCurrentState());
794
795     // Apply the layer's transform, followed by the display's global transform
796     // Here we're guaranteed that the layer's transform preserves rects
797     Rect win(s.active.w, s.active.h);
798     if (!s.crop.isEmpty()) {
799         win.intersect(s.crop, &win);
800     }
801     // Subtract the transparent region and snap to the bounds
802     Rect bounds = reduce(win, s.activeTransparentRegion);
803     Rect frame(s.active.transform.transform(bounds));
804     frame.intersect(displayDevice->getViewport(), &frame);
805     if (!s.finalCrop.isEmpty()) {
806         frame.intersect(s.finalCrop, &frame);
807     }
808     auto& displayTransform(displayDevice->getTransform());
809     auto position = displayTransform.transform(frame);
810
811     auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
812             position.top);
813     ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
814             "to (%d, %d): %s (%d)", mName.string(), position.left,
815             position.top, to_string(error).c_str(),
816             static_cast<int32_t>(error));
817 }
818 #else
819 void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
820         HWComposer::HWCLayerInterface& layer) {
821     int fenceFd = -1;
822
823     // TODO: there is a possible optimization here: we only need to set the
824     // acquire fence the first time a new buffer is acquired on EACH display.
825
826     if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
827         sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
828         if (fence->isValid()) {
829             fenceFd = fence->dup();
830             if (fenceFd == -1) {
831                 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
832             }
833         }
834     }
835     setAcquiredFenceIfBlit(fenceFd, layer);
836     layer.setAcquireFenceFd(fenceFd);
837 }
838
839 Rect Layer::getPosition(
840     const sp<const DisplayDevice>& hw)
841 {
842     // this gives us only the "orientation" component of the transform
843     const State& s(getCurrentState());
844
845     // apply the layer's transform, followed by the display's global transform
846     // here we're guaranteed that the layer's transform preserves rects
847     Rect win(s.active.w, s.active.h);
848     if (!s.crop.isEmpty()) {
849         win.intersect(s.crop, &win);
850     }
851     // subtract the transparent region and snap to the bounds
852     Rect bounds = reduce(win, s.activeTransparentRegion);
853     Rect frame(s.active.transform.transform(bounds));
854     frame.intersect(hw->getViewport(), &frame);
855     if (!s.finalCrop.isEmpty()) {
856         frame.intersect(s.finalCrop, &frame);
857     }
858     const Transform& tr(hw->getTransform());
859     return Rect(tr.transform(frame));
860 }
861 #endif
862
863 // ---------------------------------------------------------------------------
864 // drawing...
865 // ---------------------------------------------------------------------------
866
867 void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
868     onDraw(hw, clip, false);
869 }
870
871 void Layer::draw(const sp<const DisplayDevice>& hw,
872         bool useIdentityTransform) const {
873     onDraw(hw, Region(hw->bounds()), useIdentityTransform);
874 }
875
876 void Layer::draw(const sp<const DisplayDevice>& hw) const {
877     onDraw(hw, Region(hw->bounds()), false);
878 }
879
880 void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
881         bool useIdentityTransform) const
882 {
883     ATRACE_CALL();
884
885     if (CC_UNLIKELY(mActiveBuffer == 0)) {
886         // the texture has not been created yet, this Layer has
887         // in fact never been drawn into. This happens frequently with
888         // SurfaceView because the WindowManager can't know when the client
889         // has drawn the first time.
890
891         // If there is nothing under us, we paint the screen in black, otherwise
892         // we just skip this update.
893
894         // figure out if there is something below us
895         Region under;
896         const SurfaceFlinger::LayerVector& drawingLayers(
897                 mFlinger->mDrawingState.layersSortedByZ);
898         const size_t count = drawingLayers.size();
899         for (size_t i=0 ; i<count ; ++i) {
900             const sp<Layer>& layer(drawingLayers[i]);
901             if (layer.get() == static_cast<Layer const*>(this))
902                 break;
903             under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
904         }
905         // if not everything below us is covered, we plug the holes!
906         Region holes(clip.subtract(under));
907         if (!holes.isEmpty()) {
908             clearWithOpenGL(hw, holes, 0, 0, 0, 1);
909         }
910         return;
911     }
912
913     // Bind the current buffer to the GL texture, and wait for it to be
914     // ready for us to draw into.
915     status_t err = mSurfaceFlingerConsumer->bindTextureImage();
916     if (err != NO_ERROR) {
917         ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
918         // Go ahead and draw the buffer anyway; no matter what we do the screen
919         // is probably going to have something visibly wrong.
920     }
921
922     bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
923
924     RenderEngine& engine(mFlinger->getRenderEngine());
925
926     if (!blackOutLayer ||
927             ((hw->getDisplayType() == HWC_DISPLAY_PRIMARY) && canAllowGPUForProtected())) {
928         // TODO: we could be more subtle with isFixedSize()
929         const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
930
931         // Query the texture matrix given our current filtering mode.
932         float textureMatrix[16];
933         mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
934         mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
935
936         if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
937
938             /*
939              * the code below applies the primary display's inverse transform to
940              * the texture transform
941              */
942
943             // create a 4x4 transform matrix from the display transform flags
944             const mat4 flipH(-1,0,0,0,  0,1,0,0, 0,0,1,0, 1,0,0,1);
945             const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
946             const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
947
948             mat4 tr;
949             uint32_t transform =
950                     DisplayDevice::getPrimaryDisplayOrientationTransform();
951             if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90)
952                 tr = tr * rot90;
953             if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H)
954                 tr = tr * flipH;
955             if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V)
956                 tr = tr * flipV;
957
958             // calculate the inverse
959             tr = inverse(tr);
960
961             // and finally apply it to the original texture matrix
962             const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
963             memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
964         }
965
966         // Set things up for texturing.
967         mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
968         mTexture.setFiltering(useFiltering);
969         mTexture.setMatrix(textureMatrix);
970
971         engine.setupLayerTexturing(mTexture);
972     } else {
973         engine.setupLayerBlackedOut();
974     }
975     drawWithOpenGL(hw, clip, useIdentityTransform);
976     engine.disableTexturing();
977 }
978
979
980 void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
981         const Region& /* clip */, float red, float green, float blue,
982         float alpha) const
983 {
984     RenderEngine& engine(mFlinger->getRenderEngine());
985     computeGeometry(hw, mMesh, false);
986     engine.setupFillWithColor(red, green, blue, alpha);
987     engine.drawMesh(mMesh);
988 }
989
990 void Layer::clearWithOpenGL(
991         const sp<const DisplayDevice>& hw, const Region& clip) const {
992     clearWithOpenGL(hw, clip, 0,0,0,0);
993 }
994
995 void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
996         const Region& /* clip */, bool useIdentityTransform) const {
997     const State& s(getDrawingState());
998
999     computeGeometry(hw, mMesh, useIdentityTransform);
1000
1001     /*
1002      * NOTE: the way we compute the texture coordinates here produces
1003      * different results than when we take the HWC path -- in the later case
1004      * the "source crop" is rounded to texel boundaries.
1005      * This can produce significantly different results when the texture
1006      * is scaled by a large amount.
1007      *
1008      * The GL code below is more logical (imho), and the difference with
1009      * HWC is due to a limitation of the HWC API to integers -- a question
1010      * is suspend is whether we should ignore this problem or revert to
1011      * GL composition when a buffer scaling is applied (maybe with some
1012      * minimal value)? Or, we could make GL behave like HWC -- but this feel
1013      * like more of a hack.
1014      */
1015 #ifdef QTI_BSP
1016     Rect win(s.active.w, s.active.h);
1017
1018     if (!s.crop.isEmpty()) {
1019         win = s.crop;
1020     }
1021
1022     win = s.active.transform.transform(win);
1023     win.intersect(hw->getViewport(), &win);
1024     win = s.active.transform.inverse().transform(win);
1025     win.intersect(Rect(s.active.w, s.active.h), &win);
1026     win = reduce(win, s.activeTransparentRegion);
1027 #else
1028     Rect win(computeBounds());
1029
1030     if (!s.finalCrop.isEmpty()) {
1031         win = s.active.transform.transform(win);
1032         if (!win.intersect(s.finalCrop, &win)) {
1033             win.clear();
1034         }
1035         win = s.active.transform.inverse().transform(win);
1036         if (!win.intersect(computeBounds(), &win)) {
1037             win.clear();
1038         }
1039     }
1040 #endif
1041     float left   = float(win.left)   / float(s.active.w);
1042     float top    = float(win.top)    / float(s.active.h);
1043     float right  = float(win.right)  / float(s.active.w);
1044     float bottom = float(win.bottom) / float(s.active.h);
1045
1046     // TODO: we probably want to generate the texture coords with the mesh
1047     // here we assume that we only have 4 vertices
1048     Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1049     texCoords[0] = vec2(left, 1.0f - top);
1050     texCoords[1] = vec2(left, 1.0f - bottom);
1051     texCoords[2] = vec2(right, 1.0f - bottom);
1052     texCoords[3] = vec2(right, 1.0f - top);
1053
1054     RenderEngine& engine(mFlinger->getRenderEngine());
1055     engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), s.alpha);
1056     engine.drawMesh(mMesh);
1057     engine.disableBlending();
1058 }
1059
1060 #ifdef USE_HWC2
1061 void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1062         bool callIntoHwc) {
1063     if (mHwcLayers.count(hwcId) == 0) {
1064         ALOGE("setCompositionType called without a valid HWC layer");
1065         return;
1066     }
1067     auto& hwcInfo = mHwcLayers[hwcId];
1068     auto& hwcLayer = hwcInfo.layer;
1069     ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1070             to_string(type).c_str(), static_cast<int>(callIntoHwc));
1071     if (hwcInfo.compositionType != type) {
1072         ALOGV("    actually setting");
1073         hwcInfo.compositionType = type;
1074         if (callIntoHwc) {
1075             auto error = hwcLayer->setCompositionType(type);
1076             ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1077                     "composition type %s: %s (%d)", mName.string(),
1078                     to_string(type).c_str(), to_string(error).c_str(),
1079                     static_cast<int32_t>(error));
1080         }
1081     }
1082 }
1083
1084 HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
1085     if (mHwcLayers.count(hwcId) == 0) {
1086         ALOGE("getCompositionType called without a valid HWC layer");
1087         return HWC2::Composition::Invalid;
1088     }
1089     return mHwcLayers.at(hwcId).compositionType;
1090 }
1091
1092 void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1093     if (mHwcLayers.count(hwcId) == 0) {
1094         ALOGE("setClearClientTarget called without a valid HWC layer");
1095         return;
1096     }
1097     mHwcLayers[hwcId].clearClientTarget = clear;
1098 }
1099
1100 bool Layer::getClearClientTarget(int32_t hwcId) const {
1101     if (mHwcLayers.count(hwcId) == 0) {
1102         ALOGE("getClearClientTarget called without a valid HWC layer");
1103         return false;
1104     }
1105     return mHwcLayers.at(hwcId).clearClientTarget;
1106 }
1107 #endif
1108
1109 uint32_t Layer::getProducerStickyTransform() const {
1110     int producerStickyTransform = 0;
1111     int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1112     if (ret != OK) {
1113         ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1114                 strerror(-ret), ret);
1115         return 0;
1116     }
1117     return static_cast<uint32_t>(producerStickyTransform);
1118 }
1119
1120 uint64_t Layer::getHeadFrameNumber() const {
1121     Mutex::Autolock lock(mQueueItemLock);
1122     if (!mQueueItems.empty()) {
1123         return mQueueItems[0].mFrameNumber;
1124     } else {
1125         return mCurrentFrameNumber;
1126     }
1127 }
1128
1129 bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1130     if (point->getFrameNumber() <= mCurrentFrameNumber) {
1131         // Don't bother with a SyncPoint, since we've already latched the
1132         // relevant frame
1133         return false;
1134     }
1135
1136     Mutex::Autolock lock(mLocalSyncPointMutex);
1137     mLocalSyncPoints.push_back(point);
1138     return true;
1139 }
1140
1141 void Layer::setFiltering(bool filtering) {
1142     mFiltering = filtering;
1143 }
1144
1145 bool Layer::getFiltering() const {
1146     return mFiltering;
1147 }
1148
1149 // As documented in libhardware header, formats in the range
1150 // 0x100 - 0x1FF are specific to the HAL implementation, and
1151 // are known to have no alpha channel
1152 // TODO: move definition for device-specific range into
1153 // hardware.h, instead of using hard-coded values here.
1154 #define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1155
1156 bool Layer::getOpacityForFormat(uint32_t format) {
1157     if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1158         return true;
1159     }
1160     switch (format) {
1161         case HAL_PIXEL_FORMAT_RGBA_8888:
1162         case HAL_PIXEL_FORMAT_BGRA_8888:
1163             return false;
1164     }
1165     // in all other case, we have no blending (also for unknown formats)
1166     return true;
1167 }
1168
1169 // ----------------------------------------------------------------------------
1170 // local state
1171 // ----------------------------------------------------------------------------
1172
1173 static void boundPoint(vec2* point, const Rect& crop) {
1174     if (point->x < crop.left) {
1175         point->x = crop.left;
1176     }
1177     if (point->x > crop.right) {
1178         point->x = crop.right;
1179     }
1180     if (point->y < crop.top) {
1181         point->y = crop.top;
1182     }
1183     if (point->y > crop.bottom) {
1184         point->y = crop.bottom;
1185     }
1186 }
1187
1188 void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1189         bool useIdentityTransform) const
1190 {
1191     const Layer::State& s(getDrawingState());
1192     const Transform tr(hw->getTransform());
1193     const uint32_t hw_h = hw->getHeight();
1194     Rect win(s.active.w, s.active.h);
1195     if (!s.crop.isEmpty()) {
1196         win.intersect(s.crop, &win);
1197     }
1198 #ifdef QTI_BSP
1199     win = s.active.transform.transform(win);
1200     win.intersect(hw->getViewport(), &win);
1201     win = s.active.transform.inverse().transform(win);
1202     win.intersect(Rect(s.active.w, s.active.h), &win);
1203     win = reduce(win, s.activeTransparentRegion);
1204
1205     const Transform bufferOrientation(mCurrentTransform);
1206     Transform transform(tr * s.active.transform * bufferOrientation);
1207     if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
1208         uint32_t invTransform =  DisplayDevice::getPrimaryDisplayOrientationTransform();
1209          if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
1210               invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
1211                       NATIVE_WINDOW_TRANSFORM_FLIP_H;
1212          }
1213           transform = Transform(invTransform) * transform;
1214     }
1215     const uint32_t orientation = transform.getOrientation();
1216     if (!(orientation | mCurrentTransform | mTransformHint)) {
1217         if (!useIdentityTransform) {
1218             win = s.active.transform.transform(win);
1219             win.intersect(hw->getViewport(), &win);
1220         }
1221     }
1222 #else
1223     win = reduce(win, s.activeTransparentRegion);
1224 #endif
1225
1226
1227
1228     // subtract the transparent region and snap to the bounds
1229
1230     vec2 lt = vec2(win.left, win.top);
1231     vec2 lb = vec2(win.left, win.bottom);
1232     vec2 rb = vec2(win.right, win.bottom);
1233     vec2 rt = vec2(win.right, win.top);
1234
1235     if (!useIdentityTransform) {
1236 #ifdef QTI_BSP
1237         if (orientation | mCurrentTransform | mTransformHint) {
1238             lt = s.active.transform.transform(lt);
1239             lb = s.active.transform.transform(lb);
1240             rb = s.active.transform.transform(rb);
1241             rt = s.active.transform.transform(rt);
1242         }
1243 #else
1244             lt = s.active.transform.transform(lt);
1245             lb = s.active.transform.transform(lb);
1246             rb = s.active.transform.transform(rb);
1247             rt = s.active.transform.transform(rt);
1248 #endif
1249     }
1250     if (!s.finalCrop.isEmpty()) {
1251         boundPoint(&lt, s.finalCrop);
1252         boundPoint(&lb, s.finalCrop);
1253         boundPoint(&rb, s.finalCrop);
1254         boundPoint(&rt, s.finalCrop);
1255     }
1256
1257     Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
1258     position[0] = tr.transform(lt);
1259     position[1] = tr.transform(lb);
1260     position[2] = tr.transform(rb);
1261     position[3] = tr.transform(rt);
1262     for (size_t i=0 ; i<4 ; i++) {
1263         position[i].y = hw_h - position[i].y;
1264     }
1265 }
1266
1267 bool Layer::isOpaque(const Layer::State& s) const
1268 {
1269     // if we don't have a buffer yet, we're translucent regardless of the
1270     // layer's opaque flag.
1271     if (mActiveBuffer == 0) {
1272         return false;
1273     }
1274
1275     // if the layer has the opaque flag, then we're always opaque,
1276     // otherwise we use the current buffer's format.
1277     return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
1278 }
1279
1280 bool Layer::isSecure() const
1281 {
1282     const Layer::State& s(mDrawingState);
1283     return (s.flags & layer_state_t::eLayerSecure);
1284 }
1285
1286 bool Layer::isProtected() const
1287 {
1288     const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
1289     return (activeBuffer != 0) &&
1290             (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1291 }
1292
1293 bool Layer::isFixedSize() const {
1294     return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
1295 }
1296
1297 bool Layer::isCropped() const {
1298     return !mCurrentCrop.isEmpty();
1299 }
1300
1301 bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1302     return mNeedsFiltering || hw->needsFiltering();
1303 }
1304
1305 void Layer::setVisibleRegion(const Region& visibleRegion) {
1306     // always called from main thread
1307     this->visibleRegion = visibleRegion;
1308 }
1309
1310 void Layer::setCoveredRegion(const Region& coveredRegion) {
1311     // always called from main thread
1312     this->coveredRegion = coveredRegion;
1313 }
1314
1315 void Layer::setVisibleNonTransparentRegion(const Region&
1316         setVisibleNonTransparentRegion) {
1317     // always called from main thread
1318     this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1319 }
1320
1321 // ----------------------------------------------------------------------------
1322 // transaction
1323 // ----------------------------------------------------------------------------
1324
1325 void Layer::pushPendingState() {
1326     if (!mCurrentState.modified) {
1327         return;
1328     }
1329
1330     // If this transaction is waiting on the receipt of a frame, generate a sync
1331     // point and send it to the remote layer.
1332     if (mCurrentState.handle != nullptr) {
1333         sp<Handle> handle = static_cast<Handle*>(mCurrentState.handle.get());
1334         sp<Layer> handleLayer = handle->owner.promote();
1335         if (handleLayer == nullptr) {
1336             ALOGE("[%s] Unable to promote Layer handle", mName.string());
1337             // If we can't promote the layer we are intended to wait on,
1338             // then it is expired or otherwise invalid. Allow this transaction
1339             // to be applied as per normal (no synchronization).
1340             mCurrentState.handle = nullptr;
1341         } else {
1342             auto syncPoint = std::make_shared<SyncPoint>(
1343                     mCurrentState.frameNumber);
1344             if (handleLayer->addSyncPoint(syncPoint)) {
1345                 mRemoteSyncPoints.push_back(std::move(syncPoint));
1346             } else {
1347                 // We already missed the frame we're supposed to synchronize
1348                 // on, so go ahead and apply the state update
1349                 mCurrentState.handle = nullptr;
1350             }
1351         }
1352
1353         // Wake us up to check if the frame has been received
1354         setTransactionFlags(eTransactionNeeded);
1355     }
1356     mPendingStates.push_back(mCurrentState);
1357 }
1358
1359 void Layer::popPendingState(State* stateToCommit) {
1360     auto oldFlags = stateToCommit->flags;
1361     *stateToCommit = mPendingStates[0];
1362     stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1363             (stateToCommit->flags & stateToCommit->mask);
1364
1365     mPendingStates.removeAt(0);
1366 }
1367
1368 bool Layer::applyPendingStates(State* stateToCommit) {
1369     bool stateUpdateAvailable = false;
1370     while (!mPendingStates.empty()) {
1371         if (mPendingStates[0].handle != nullptr) {
1372             if (mRemoteSyncPoints.empty()) {
1373                 // If we don't have a sync point for this, apply it anyway. It
1374                 // will be visually wrong, but it should keep us from getting
1375                 // into too much trouble.
1376                 ALOGE("[%s] No local sync point found", mName.string());
1377                 popPendingState(stateToCommit);
1378                 stateUpdateAvailable = true;
1379                 continue;
1380             }
1381
1382             if (mRemoteSyncPoints.front()->getFrameNumber() !=
1383                     mPendingStates[0].frameNumber) {
1384                 ALOGE("[%s] Unexpected sync point frame number found",
1385                         mName.string());
1386
1387                 // Signal our end of the sync point and then dispose of it
1388                 mRemoteSyncPoints.front()->setTransactionApplied();
1389                 mRemoteSyncPoints.pop_front();
1390                 continue;
1391             }
1392
1393             if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1394                 // Apply the state update
1395                 popPendingState(stateToCommit);
1396                 stateUpdateAvailable = true;
1397
1398                 // Signal our end of the sync point and then dispose of it
1399                 mRemoteSyncPoints.front()->setTransactionApplied();
1400                 mRemoteSyncPoints.pop_front();
1401             } else {
1402                 break;
1403             }
1404         } else {
1405             popPendingState(stateToCommit);
1406             stateUpdateAvailable = true;
1407         }
1408     }
1409
1410     // If we still have pending updates, wake SurfaceFlinger back up and point
1411     // it at this layer so we can process them
1412     if (!mPendingStates.empty()) {
1413         setTransactionFlags(eTransactionNeeded);
1414         mFlinger->setTransactionFlags(eTraversalNeeded);
1415     }
1416
1417     mCurrentState.modified = false;
1418     return stateUpdateAvailable;
1419 }
1420
1421 void Layer::notifyAvailableFrames() {
1422     auto headFrameNumber = getHeadFrameNumber();
1423     Mutex::Autolock lock(mLocalSyncPointMutex);
1424     for (auto& point : mLocalSyncPoints) {
1425         if (headFrameNumber >= point->getFrameNumber()) {
1426             point->setFrameAvailable();
1427         }
1428     }
1429 }
1430
1431 uint32_t Layer::doTransaction(uint32_t flags) {
1432     ATRACE_CALL();
1433
1434     pushPendingState();
1435     Layer::State c = getCurrentState();
1436     if (!applyPendingStates(&c)) {
1437         return 0;
1438     }
1439
1440     const Layer::State& s(getDrawingState());
1441
1442     const bool sizeChanged = (c.requested.w != s.requested.w) ||
1443                              (c.requested.h != s.requested.h);
1444
1445     if (sizeChanged) {
1446         // the size changed, we need to ask our client to request a new buffer
1447         ALOGD_IF(DEBUG_RESIZE,
1448                 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
1449                 "  current={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1450                 "            requested={ wh={%4u,%4u} }}\n"
1451                 "  drawing={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1452                 "            requested={ wh={%4u,%4u} }}\n",
1453                 this, getName().string(), mCurrentTransform,
1454                 getEffectiveScalingMode(),
1455                 c.active.w, c.active.h,
1456                 c.crop.left,
1457                 c.crop.top,
1458                 c.crop.right,
1459                 c.crop.bottom,
1460                 c.crop.getWidth(),
1461                 c.crop.getHeight(),
1462                 c.requested.w, c.requested.h,
1463                 s.active.w, s.active.h,
1464                 s.crop.left,
1465                 s.crop.top,
1466                 s.crop.right,
1467                 s.crop.bottom,
1468                 s.crop.getWidth(),
1469                 s.crop.getHeight(),
1470                 s.requested.w, s.requested.h);
1471
1472         // record the new size, form this point on, when the client request
1473         // a buffer, it'll get the new size.
1474         mSurfaceFlingerConsumer->setDefaultBufferSize(
1475                 c.requested.w, c.requested.h);
1476     }
1477
1478     const bool resizePending = (c.requested.w != c.active.w) ||
1479             (c.requested.h != c.active.h);
1480     if (!isFixedSize()) {
1481         if (resizePending && mSidebandStream == NULL) {
1482             // don't let Layer::doTransaction update the drawing state
1483             // if we have a pending resize, unless we are in fixed-size mode.
1484             // the drawing state will be updated only once we receive a buffer
1485             // with the correct size.
1486             //
1487             // in particular, we want to make sure the clip (which is part
1488             // of the geometry state) is latched together with the size but is
1489             // latched immediately when no resizing is involved.
1490             //
1491             // If a sideband stream is attached, however, we want to skip this
1492             // optimization so that transactions aren't missed when a buffer
1493             // never arrives
1494
1495             flags |= eDontUpdateGeometryState;
1496         }
1497     }
1498
1499     // always set active to requested, unless we're asked not to
1500     // this is used by Layer, which special cases resizes.
1501     if (flags & eDontUpdateGeometryState)  {
1502     } else {
1503         Layer::State& editCurrentState(getCurrentState());
1504         if (mFreezePositionUpdates) {
1505             float tx = c.active.transform.tx();
1506             float ty = c.active.transform.ty();
1507             c.active = c.requested;
1508             c.active.transform.set(tx, ty);
1509             editCurrentState.active = c.active;
1510         } else {
1511             editCurrentState.active = editCurrentState.requested;
1512             c.active = c.requested;
1513         }
1514     }
1515
1516     if (s.active != c.active) {
1517         // invalidate and recompute the visible regions if needed
1518         flags |= Layer::eVisibleRegion;
1519     }
1520
1521     if (c.sequence != s.sequence) {
1522         // invalidate and recompute the visible regions if needed
1523         flags |= eVisibleRegion;
1524         this->contentDirty = true;
1525
1526         // we may use linear filtering, if the matrix scales us
1527         const uint8_t type = c.active.transform.getType();
1528         mNeedsFiltering = (!c.active.transform.preserveRects() ||
1529                 (type >= Transform::SCALE));
1530     }
1531
1532     // If the layer is hidden, signal and clear out all local sync points so
1533     // that transactions for layers depending on this layer's frames becoming
1534     // visible are not blocked
1535     if (c.flags & layer_state_t::eLayerHidden) {
1536         Mutex::Autolock lock(mLocalSyncPointMutex);
1537         for (auto& point : mLocalSyncPoints) {
1538             point->setFrameAvailable();
1539         }
1540         mLocalSyncPoints.clear();
1541     }
1542
1543     // Commit the transaction
1544     commitTransaction(c);
1545     return flags;
1546 }
1547
1548 void Layer::commitTransaction(const State& stateToCommit) {
1549     mDrawingState = stateToCommit;
1550 }
1551
1552 uint32_t Layer::getTransactionFlags(uint32_t flags) {
1553     return android_atomic_and(~flags, &mTransactionFlags) & flags;
1554 }
1555
1556 uint32_t Layer::setTransactionFlags(uint32_t flags) {
1557     return android_atomic_or(flags, &mTransactionFlags);
1558 }
1559
1560 bool Layer::setPosition(float x, float y, bool immediate) {
1561     if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
1562         return false;
1563     mCurrentState.sequence++;
1564
1565     // We update the requested and active position simultaneously because
1566     // we want to apply the position portion of the transform matrix immediately,
1567     // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
1568     mCurrentState.requested.transform.set(x, y);
1569     if (immediate && !mFreezePositionUpdates) {
1570         mCurrentState.active.transform.set(x, y);
1571     }
1572     mFreezePositionUpdates = mFreezePositionUpdates || !immediate;
1573
1574     mCurrentState.modified = true;
1575     setTransactionFlags(eTransactionNeeded);
1576     return true;
1577 }
1578
1579 bool Layer::setLayer(uint32_t z) {
1580     if (mCurrentState.z == z)
1581         return false;
1582     mCurrentState.sequence++;
1583     mCurrentState.z = z;
1584     mCurrentState.modified = true;
1585     setTransactionFlags(eTransactionNeeded);
1586     return true;
1587 }
1588 bool Layer::setSize(uint32_t w, uint32_t h) {
1589     if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1590         return false;
1591     mCurrentState.requested.w = w;
1592     mCurrentState.requested.h = h;
1593     mCurrentState.modified = true;
1594     setTransactionFlags(eTransactionNeeded);
1595     return true;
1596 }
1597 #ifdef USE_HWC2
1598 bool Layer::setAlpha(float alpha) {
1599 #else
1600 bool Layer::setAlpha(uint8_t alpha) {
1601 #endif
1602     if (mCurrentState.alpha == alpha)
1603         return false;
1604     mCurrentState.sequence++;
1605     mCurrentState.alpha = alpha;
1606     mCurrentState.modified = true;
1607     setTransactionFlags(eTransactionNeeded);
1608     return true;
1609 }
1610 bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1611     mCurrentState.sequence++;
1612     mCurrentState.requested.transform.set(
1613             matrix.dsdx, matrix.dsdy, matrix.dtdx, matrix.dtdy);
1614     mCurrentState.modified = true;
1615     setTransactionFlags(eTransactionNeeded);
1616     return true;
1617 }
1618 bool Layer::setTransparentRegionHint(const Region& transparent) {
1619     mCurrentState.requestedTransparentRegion = transparent;
1620     mCurrentState.modified = true;
1621     setTransactionFlags(eTransactionNeeded);
1622     return true;
1623 }
1624 bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1625     const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1626     if (mCurrentState.flags == newFlags)
1627         return false;
1628     mCurrentState.sequence++;
1629     mCurrentState.flags = newFlags;
1630     mCurrentState.mask = mask;
1631     mCurrentState.modified = true;
1632     setTransactionFlags(eTransactionNeeded);
1633     return true;
1634 }
1635 bool Layer::setCrop(const Rect& crop) {
1636     if (mCurrentState.crop == crop)
1637         return false;
1638     mCurrentState.sequence++;
1639     mCurrentState.crop = crop;
1640     mCurrentState.modified = true;
1641     setTransactionFlags(eTransactionNeeded);
1642     return true;
1643 }
1644 bool Layer::setFinalCrop(const Rect& crop) {
1645     if (mCurrentState.finalCrop == crop)
1646         return false;
1647     mCurrentState.sequence++;
1648     mCurrentState.finalCrop = crop;
1649     mCurrentState.modified = true;
1650     setTransactionFlags(eTransactionNeeded);
1651     return true;
1652 }
1653
1654 bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1655     if (scalingMode == mOverrideScalingMode)
1656         return false;
1657     mOverrideScalingMode = scalingMode;
1658     setTransactionFlags(eTransactionNeeded);
1659     return true;
1660 }
1661
1662 bool Layer::setColor(uint32_t color) {
1663     if (mCurrentState.color == color)
1664         return false;
1665     mCurrentState.sequence++;
1666     mCurrentState.color = color;
1667     mCurrentState.modified = true;
1668     setTransactionFlags(eTransactionNeeded);
1669     return true;
1670 }
1671
1672 uint32_t Layer::getEffectiveScalingMode() const {
1673     if (mOverrideScalingMode >= 0) {
1674       return mOverrideScalingMode;
1675     }
1676     return mCurrentScalingMode;
1677 }
1678
1679 bool Layer::setLayerStack(uint32_t layerStack) {
1680     if (mCurrentState.layerStack == layerStack)
1681         return false;
1682     mCurrentState.sequence++;
1683     mCurrentState.layerStack = layerStack;
1684     mCurrentState.modified = true;
1685     setTransactionFlags(eTransactionNeeded);
1686     return true;
1687 }
1688
1689 void Layer::deferTransactionUntil(const sp<IBinder>& handle,
1690         uint64_t frameNumber) {
1691     mCurrentState.handle = handle;
1692     mCurrentState.frameNumber = frameNumber;
1693     // We don't set eTransactionNeeded, because just receiving a deferral
1694     // request without any other state updates shouldn't actually induce a delay
1695     mCurrentState.modified = true;
1696     pushPendingState();
1697     mCurrentState.handle = nullptr;
1698     mCurrentState.frameNumber = 0;
1699     mCurrentState.modified = false;
1700 }
1701
1702 void Layer::useSurfaceDamage() {
1703     if (mFlinger->mForceFullDamage) {
1704         surfaceDamageRegion = Region::INVALID_REGION;
1705     } else {
1706         surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1707     }
1708 }
1709
1710 void Layer::useEmptyDamage() {
1711     surfaceDamageRegion.clear();
1712 }
1713
1714 // ----------------------------------------------------------------------------
1715 // pageflip handling...
1716 // ----------------------------------------------------------------------------
1717
1718 bool Layer::shouldPresentNow(const DispSync& dispSync) const {
1719     if (mSidebandStreamChanged || mAutoRefresh) {
1720         return true;
1721     }
1722
1723     Mutex::Autolock lock(mQueueItemLock);
1724     if (mQueueItems.empty()) {
1725         return false;
1726     }
1727     auto timestamp = mQueueItems[0].mTimestamp;
1728     nsecs_t expectedPresent =
1729             mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
1730
1731     // Ignore timestamps more than a second in the future
1732     bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1733     ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1734             "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1735             expectedPresent);
1736
1737     bool isDue = timestamp < expectedPresent;
1738     return isDue || !isPlausible;
1739 }
1740
1741 bool Layer::onPreComposition() {
1742     mRefreshPending = false;
1743     return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
1744 }
1745
1746 void Layer::onPostComposition() {
1747     if (mFrameLatencyNeeded) {
1748         nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
1749         mFrameTracker.setDesiredPresentTime(desiredPresentTime);
1750
1751         sp<Fence> frameReadyFence = mSurfaceFlingerConsumer->getCurrentFence();
1752         if (frameReadyFence->isValid()) {
1753             mFrameTracker.setFrameReadyFence(frameReadyFence);
1754         } else {
1755             // There was no fence for this frame, so assume that it was ready
1756             // to be presented at the desired present time.
1757             mFrameTracker.setFrameReadyTime(desiredPresentTime);
1758         }
1759
1760         const HWComposer& hwc = mFlinger->getHwComposer();
1761 #ifdef USE_HWC2
1762         sp<Fence> presentFence = hwc.getRetireFence(HWC_DISPLAY_PRIMARY);
1763 #else
1764         sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
1765 #endif
1766         if (presentFence->isValid()) {
1767             mFrameTracker.setActualPresentFence(presentFence);
1768         } else {
1769             // The HWC doesn't support present fences, so use the refresh
1770             // timestamp instead.
1771             nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
1772             mFrameTracker.setActualPresentTime(presentTime);
1773         }
1774
1775         mFrameTracker.advanceFrame();
1776         mFrameLatencyNeeded = false;
1777     }
1778 }
1779
1780 #ifdef USE_HWC2
1781 void Layer::releasePendingBuffer() {
1782     mSurfaceFlingerConsumer->releasePendingBuffer();
1783 }
1784 #endif
1785
1786 bool Layer::isVisible() const {
1787     const Layer::State& s(mDrawingState);
1788 #ifdef USE_HWC2
1789     return !(s.flags & layer_state_t::eLayerHidden) && s.alpha > 0.0f
1790             && (mActiveBuffer != NULL || mSidebandStream != NULL);
1791 #else
1792     return !(s.flags & layer_state_t::eLayerHidden) && s.alpha
1793             && (mActiveBuffer != NULL || mSidebandStream != NULL);
1794 #endif
1795 }
1796
1797 Region Layer::latchBuffer(bool& recomputeVisibleRegions)
1798 {
1799     ATRACE_CALL();
1800
1801     if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
1802         // mSidebandStreamChanged was true
1803         mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
1804         if (mSidebandStream != NULL) {
1805             setTransactionFlags(eTransactionNeeded);
1806             mFlinger->setTransactionFlags(eTraversalNeeded);
1807         }
1808         recomputeVisibleRegions = true;
1809
1810         const State& s(getDrawingState());
1811         return s.active.transform.transform(Region(Rect(s.active.w, s.active.h)));
1812     }
1813
1814     Region outDirtyRegion;
1815     if (mQueuedFrames > 0 || mAutoRefresh) {
1816
1817         // if we've already called updateTexImage() without going through
1818         // a composition step, we have to skip this layer at this point
1819         // because we cannot call updateTeximage() without a corresponding
1820         // compositionComplete() call.
1821         // we'll trigger an update in onPreComposition().
1822         if (mRefreshPending) {
1823             return outDirtyRegion;
1824         }
1825
1826         // Capture the old state of the layer for comparisons later
1827         const State& s(getDrawingState());
1828         const bool oldOpacity = isOpaque(s);
1829         sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
1830
1831         struct Reject : public SurfaceFlingerConsumer::BufferRejecter {
1832             Layer::State& front;
1833             Layer::State& current;
1834             bool& recomputeVisibleRegions;
1835             bool stickyTransformSet;
1836             const char* name;
1837             int32_t overrideScalingMode;
1838
1839             Reject(Layer::State& front, Layer::State& current,
1840                     bool& recomputeVisibleRegions, bool stickySet,
1841                     const char* name,
1842                     int32_t overrideScalingMode)
1843                 : front(front), current(current),
1844                   recomputeVisibleRegions(recomputeVisibleRegions),
1845                   stickyTransformSet(stickySet),
1846                   name(name),
1847                   overrideScalingMode(overrideScalingMode) {
1848             }
1849
1850             virtual bool reject(const sp<GraphicBuffer>& buf,
1851                     const BufferItem& item) {
1852                 if (buf == NULL) {
1853                     return false;
1854                 }
1855
1856                 uint32_t bufWidth  = buf->getWidth();
1857                 uint32_t bufHeight = buf->getHeight();
1858
1859                 // check that we received a buffer of the right size
1860                 // (Take the buffer's orientation into account)
1861                 if (item.mTransform & Transform::ROT_90) {
1862                     swap(bufWidth, bufHeight);
1863                 }
1864
1865                 int actualScalingMode = overrideScalingMode >= 0 ?
1866                         overrideScalingMode : item.mScalingMode;
1867                 bool isFixedSize = actualScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE;
1868                 if (front.active != front.requested) {
1869
1870                     if (isFixedSize ||
1871                             (bufWidth == front.requested.w &&
1872                              bufHeight == front.requested.h))
1873                     {
1874                         // Here we pretend the transaction happened by updating the
1875                         // current and drawing states. Drawing state is only accessed
1876                         // in this thread, no need to have it locked
1877                         front.active = front.requested;
1878
1879                         // We also need to update the current state so that
1880                         // we don't end-up overwriting the drawing state with
1881                         // this stale current state during the next transaction
1882                         //
1883                         // NOTE: We don't need to hold the transaction lock here
1884                         // because State::active is only accessed from this thread.
1885                         current.active = front.active;
1886                         current.modified = true;
1887
1888                         // recompute visible region
1889                         recomputeVisibleRegions = true;
1890                     }
1891
1892                     ALOGD_IF(DEBUG_RESIZE,
1893                             "[%s] latchBuffer/reject: buffer (%ux%u, tr=%02x), scalingMode=%d\n"
1894                             "  drawing={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1895                             "            requested={ wh={%4u,%4u} }}\n",
1896                             name,
1897                             bufWidth, bufHeight, item.mTransform, item.mScalingMode,
1898                             front.active.w, front.active.h,
1899                             front.crop.left,
1900                             front.crop.top,
1901                             front.crop.right,
1902                             front.crop.bottom,
1903                             front.crop.getWidth(),
1904                             front.crop.getHeight(),
1905                             front.requested.w, front.requested.h);
1906                 }
1907
1908                 if (!isFixedSize && !stickyTransformSet) {
1909                     if (front.active.w != bufWidth ||
1910                         front.active.h != bufHeight) {
1911                         // reject this buffer
1912                         ALOGE("[%s] rejecting buffer: "
1913                                 "bufWidth=%d, bufHeight=%d, front.active.{w=%d, h=%d}",
1914                                 name, bufWidth, bufHeight, front.active.w, front.active.h);
1915                         return true;
1916                     }
1917                 }
1918
1919                 // if the transparent region has changed (this test is
1920                 // conservative, but that's fine, worst case we're doing
1921                 // a bit of extra work), we latch the new one and we
1922                 // trigger a visible-region recompute.
1923                 if (!front.activeTransparentRegion.isTriviallyEqual(
1924                         front.requestedTransparentRegion)) {
1925                     front.activeTransparentRegion = front.requestedTransparentRegion;
1926
1927                     // We also need to update the current state so that
1928                     // we don't end-up overwriting the drawing state with
1929                     // this stale current state during the next transaction
1930                     //
1931                     // NOTE: We don't need to hold the transaction lock here
1932                     // because State::active is only accessed from this thread.
1933                     current.activeTransparentRegion = front.activeTransparentRegion;
1934
1935                     // recompute visible region
1936                     recomputeVisibleRegions = true;
1937                 }
1938
1939                 return false;
1940             }
1941         };
1942
1943         Reject r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
1944                 getProducerStickyTransform() != 0, mName.string(),
1945                 mOverrideScalingMode);
1946
1947
1948         // Check all of our local sync points to ensure that all transactions
1949         // which need to have been applied prior to the frame which is about to
1950         // be latched have signaled
1951
1952         auto headFrameNumber = getHeadFrameNumber();
1953         bool matchingFramesFound = false;
1954         bool allTransactionsApplied = true;
1955         {
1956             Mutex::Autolock lock(mLocalSyncPointMutex);
1957             for (auto& point : mLocalSyncPoints) {
1958                 if (point->getFrameNumber() > headFrameNumber) {
1959                     break;
1960                 }
1961
1962                 matchingFramesFound = true;
1963
1964                 if (!point->frameIsAvailable()) {
1965                     // We haven't notified the remote layer that the frame for
1966                     // this point is available yet. Notify it now, and then
1967                     // abort this attempt to latch.
1968                     point->setFrameAvailable();
1969                     allTransactionsApplied = false;
1970                     break;
1971                 }
1972
1973                 allTransactionsApplied &= point->transactionIsApplied();
1974             }
1975         }
1976
1977         if (matchingFramesFound && !allTransactionsApplied) {
1978             mFlinger->signalLayerUpdate();
1979             return outDirtyRegion;
1980         }
1981
1982         // This boolean is used to make sure that SurfaceFlinger's shadow copy
1983         // of the buffer queue isn't modified when the buffer queue is returning
1984         // BufferItem's that weren't actually queued. This can happen in shared
1985         // buffer mode.
1986         bool queuedBuffer = false;
1987         status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
1988                 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
1989                 mLastFrameNumberReceived);
1990         if (updateResult == BufferQueue::PRESENT_LATER) {
1991             // Producer doesn't want buffer to be displayed yet.  Signal a
1992             // layer update so we check again at the next opportunity.
1993             mFlinger->signalLayerUpdate();
1994             return outDirtyRegion;
1995         } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
1996             // If the buffer has been rejected, remove it from the shadow queue
1997             // and return early
1998             if (queuedBuffer) {
1999                 Mutex::Autolock lock(mQueueItemLock);
2000                 mQueueItems.removeAt(0);
2001                 android_atomic_dec(&mQueuedFrames);
2002             }
2003             return outDirtyRegion;
2004         } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2005             // This can occur if something goes wrong when trying to create the
2006             // EGLImage for this buffer. If this happens, the buffer has already
2007             // been released, so we need to clean up the queue and bug out
2008             // early.
2009             if (queuedBuffer) {
2010                 Mutex::Autolock lock(mQueueItemLock);
2011                 mQueueItems.clear();
2012                 android_atomic_and(0, &mQueuedFrames);
2013             }
2014
2015             // Once we have hit this state, the shadow queue may no longer
2016             // correctly reflect the incoming BufferQueue's contents, so even if
2017             // updateTexImage starts working, the only safe course of action is
2018             // to continue to ignore updates.
2019             mUpdateTexImageFailed = true;
2020
2021             return outDirtyRegion;
2022         }
2023
2024         if (queuedBuffer) {
2025             // Autolock scope
2026             auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2027
2028             Mutex::Autolock lock(mQueueItemLock);
2029
2030             // Remove any stale buffers that have been dropped during
2031             // updateTexImage
2032             while ((mQueuedFrames > 0) && (mQueueItems[0].mFrameNumber != currentFrameNumber)) {
2033                 mQueueItems.removeAt(0);
2034                 android_atomic_dec(&mQueuedFrames);
2035             }
2036
2037             if (mQueuedFrames == 0) {
2038                 ALOGE("[%s] mQueuedFrames is zero !!", mName.string());
2039                 return outDirtyRegion;
2040             }
2041
2042             mQueueItems.removeAt(0);
2043         }
2044
2045
2046         // Decrement the queued-frames count.  Signal another event if we
2047         // have more frames pending.
2048         if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2049                 || mAutoRefresh) {
2050             mFlinger->signalLayerUpdate();
2051         }
2052
2053         if (updateResult != NO_ERROR) {
2054             // something happened!
2055             recomputeVisibleRegions = true;
2056             return outDirtyRegion;
2057         }
2058
2059         // update the active buffer
2060         mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer();
2061         if (mActiveBuffer == NULL) {
2062             // this can only happen if the very first buffer was rejected.
2063             return outDirtyRegion;
2064         }
2065
2066         mRefreshPending = true;
2067         mFrameLatencyNeeded = true;
2068         if (oldActiveBuffer == NULL) {
2069              // the first time we receive a buffer, we need to trigger a
2070              // geometry invalidation.
2071             recomputeVisibleRegions = true;
2072          }
2073
2074         Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2075         const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2076         const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2077         if ((crop != mCurrentCrop) ||
2078             (transform != mCurrentTransform) ||
2079             (scalingMode != mCurrentScalingMode))
2080         {
2081             mCurrentCrop = crop;
2082             mCurrentTransform = transform;
2083             mCurrentScalingMode = scalingMode;
2084             recomputeVisibleRegions = true;
2085         }
2086
2087         if (oldActiveBuffer != NULL) {
2088             uint32_t bufWidth  = mActiveBuffer->getWidth();
2089             uint32_t bufHeight = mActiveBuffer->getHeight();
2090             if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2091                 bufHeight != uint32_t(oldActiveBuffer->height)) {
2092                 recomputeVisibleRegions = true;
2093                 mFreezePositionUpdates = false;
2094             }
2095         }
2096
2097         mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2098         if (oldOpacity != isOpaque(s)) {
2099             recomputeVisibleRegions = true;
2100         }
2101
2102         mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2103
2104         // Remove any sync points corresponding to the buffer which was just
2105         // latched
2106         {
2107             Mutex::Autolock lock(mLocalSyncPointMutex);
2108             auto point = mLocalSyncPoints.begin();
2109             while (point != mLocalSyncPoints.end()) {
2110                 if (!(*point)->frameIsAvailable() ||
2111                         !(*point)->transactionIsApplied()) {
2112                     // This sync point must have been added since we started
2113                     // latching. Don't drop it yet.
2114                     ++point;
2115                     continue;
2116                 }
2117
2118                 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2119                     point = mLocalSyncPoints.erase(point);
2120                 } else {
2121                     ++point;
2122                 }
2123             }
2124         }
2125
2126         // FIXME: postedRegion should be dirty & bounds
2127         Region dirtyRegion(Rect(s.active.w, s.active.h));
2128
2129         // transform the dirty region to window-manager space
2130         outDirtyRegion = (s.active.transform.transform(dirtyRegion));
2131     }
2132     return outDirtyRegion;
2133 }
2134
2135 uint32_t Layer::getEffectiveUsage(uint32_t usage) const
2136 {
2137     // TODO: should we do something special if mSecure is set?
2138     if (mProtectedByApp) {
2139         // need a hardware-protected path to external video sink
2140         usage |= GraphicBuffer::USAGE_PROTECTED;
2141     }
2142     if (mPotentialCursor) {
2143         usage |= GraphicBuffer::USAGE_CURSOR;
2144     }
2145     usage |= GraphicBuffer::USAGE_HW_COMPOSER;
2146     return usage;
2147 }
2148
2149 void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) {
2150     uint32_t orientation = 0;
2151     if (!mFlinger->mDebugDisableTransformHint) {
2152         // The transform hint is used to improve performance, but we can
2153         // only have a single transform hint, it cannot
2154         // apply to all displays.
2155         const Transform& planeTransform(hw->getTransform());
2156         orientation = planeTransform.getOrientation();
2157         if (orientation & Transform::ROT_INVALID) {
2158             orientation = 0;
2159         }
2160     }
2161     mSurfaceFlingerConsumer->setTransformHint(orientation);
2162     mTransformHint = orientation;
2163 }
2164
2165 // ----------------------------------------------------------------------------
2166 // debugging
2167 // ----------------------------------------------------------------------------
2168
2169 void Layer::dump(String8& result, Colorizer& colorizer) const
2170 {
2171     const Layer::State& s(getDrawingState());
2172
2173     colorizer.colorize(result, Colorizer::GREEN);
2174     result.appendFormat(
2175             "+ %s %p (%s)\n",
2176             getTypeId(), this, getName().string());
2177     colorizer.reset(result);
2178
2179     s.activeTransparentRegion.dump(result, "transparentRegion");
2180     visibleRegion.dump(result, "visibleRegion");
2181     surfaceDamageRegion.dump(result, "surfaceDamageRegion");
2182     sp<Client> client(mClientRef.promote());
2183
2184     result.appendFormat(            "      "
2185             "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2186             "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
2187             "isOpaque=%1d, invalidate=%1d, "
2188 #ifdef USE_HWC2
2189             "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2190 #else
2191             "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2192 #endif
2193             "      client=%p\n",
2194             s.layerStack, s.z, s.active.transform.tx(), s.active.transform.ty(), s.active.w, s.active.h,
2195             s.crop.left, s.crop.top,
2196             s.crop.right, s.crop.bottom,
2197             s.finalCrop.left, s.finalCrop.top,
2198             s.finalCrop.right, s.finalCrop.bottom,
2199             isOpaque(s), contentDirty,
2200             s.alpha, s.flags,
2201             s.active.transform[0][0], s.active.transform[0][1],
2202             s.active.transform[1][0], s.active.transform[1][1],
2203             client.get());
2204
2205     sp<const GraphicBuffer> buf0(mActiveBuffer);
2206     uint32_t w0=0, h0=0, s0=0, f0=0;
2207     if (buf0 != 0) {
2208         w0 = buf0->getWidth();
2209         h0 = buf0->getHeight();
2210         s0 = buf0->getStride();
2211         f0 = buf0->format;
2212     }
2213     result.appendFormat(
2214             "      "
2215             "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2216             " queued-frames=%d, mRefreshPending=%d\n",
2217             mFormat, w0, h0, s0,f0,
2218             mQueuedFrames, mRefreshPending);
2219
2220     if (mSurfaceFlingerConsumer != 0) {
2221         mSurfaceFlingerConsumer->dump(result, "            ");
2222     }
2223 }
2224
2225 void Layer::dumpFrameStats(String8& result) const {
2226     mFrameTracker.dumpStats(result);
2227 }
2228
2229 void Layer::clearFrameStats() {
2230     mFrameTracker.clearStats();
2231 }
2232
2233 void Layer::logFrameStats() {
2234     mFrameTracker.logAndResetStats(mName);
2235 }
2236
2237 void Layer::getFrameStats(FrameStats* outStats) const {
2238     mFrameTracker.getStats(outStats);
2239 }
2240
2241 void Layer::getFenceData(String8* outName, uint64_t* outFrameNumber,
2242         bool* outIsGlesComposition, nsecs_t* outPostedTime,
2243         sp<Fence>* outAcquireFence, sp<Fence>* outPrevReleaseFence) const {
2244     *outName = mName;
2245     *outFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2246
2247 #ifdef USE_HWC2
2248     *outIsGlesComposition = mHwcLayers.count(HWC_DISPLAY_PRIMARY) ?
2249             mHwcLayers.at(HWC_DISPLAY_PRIMARY).compositionType ==
2250             HWC2::Composition::Client : true;
2251 #else
2252     *outIsGlesComposition = mIsGlesComposition;
2253 #endif
2254     *outPostedTime = mSurfaceFlingerConsumer->getTimestamp();
2255     *outAcquireFence = mSurfaceFlingerConsumer->getCurrentFence();
2256     *outPrevReleaseFence = mSurfaceFlingerConsumer->getPrevReleaseFence();
2257 }
2258 // ---------------------------------------------------------------------------
2259
2260 Layer::LayerCleaner::LayerCleaner(const sp<SurfaceFlinger>& flinger,
2261         const sp<Layer>& layer)
2262     : mFlinger(flinger), mLayer(layer) {
2263 }
2264
2265 Layer::LayerCleaner::~LayerCleaner() {
2266     // destroy client resources
2267     mFlinger->onLayerDestroyed(mLayer);
2268 }
2269
2270 // ---------------------------------------------------------------------------
2271 }; // namespace android
2272
2273 #if defined(__gl_h_)
2274 #error "don't include gl/gl.h in this file"
2275 #endif
2276
2277 #if defined(__gl2_h_)
2278 #error "don't include gl2/gl2.h in this file"
2279 #endif