blob: 7fcc41a7be2981e9356ca943019308d295e0cc7f [file] [log] [blame]
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define ATRACE_TAG ATRACE_TAG_GRAPHICS
18
Mark Salyzyn7823e122016-09-29 08:08:05 -070019#include <dlfcn.h>
20#include <errno.h>
21#include <inttypes.h>
22#include <math.h>
23#include <stdatomic.h>
Fabien Sanglard9d96de42016-10-11 00:15:18 +000024#include <stdint.h>
25#include <sys/types.h>
Dan Stoza9e56aa02015-11-02 13:00:03 -080026
Fabien Sanglard9d96de42016-10-11 00:15:18 +000027#include <mutex>
Fabien Sanglard9d96de42016-10-11 00:15:18 +000028
29#include <EGL/egl.h>
30
Fabien Sanglard9d96de42016-10-11 00:15:18 +000031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
Fabien Sanglard9d96de42016-10-11 00:15:18 +000033
34#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
36#include <binder/MemoryHeapBase.h>
37#include <binder/PermissionCache.h>
38
39#include <ui/DisplayInfo.h>
40#include <ui/DisplayStatInfo.h>
41
42#include <gui/BitTube.h>
43#include <gui/BufferQueue.h>
44#include <gui/GuiConfig.h>
45#include <gui/IDisplayEventConnection.h>
46#include <gui/Surface.h>
47#include <gui/GraphicBufferAlloc.h>
48
49#include <ui/GraphicBufferAllocator.h>
50#include <ui/HdrCapabilities.h>
51#include <ui/PixelFormat.h>
52#include <ui/UiConfig.h>
53
54#include <utils/misc.h>
55#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
58#include <utils/Timers.h>
59#include <utils/Trace.h>
60
61#include <private/android_filesystem_config.h>
62#include <private/gui/SyncFeatures.h>
63
64#include <set>
65
66#include "Client.h"
67#include "clz.h"
68#include "Colorizer.h"
69#include "DdmConnection.h"
70#include "DisplayDevice.h"
71#include "DispSync.h"
72#include "EventControlThread.h"
73#include "EventThread.h"
74#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Fabien Sanglard9d96de42016-10-11 00:15:18 +000076#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080077#include "MonitoredProducer.h"
Fabien Sanglard9d96de42016-10-11 00:15:18 +000078#include "SurfaceFlinger.h"
79
80#include "DisplayHardware/FramebufferSurface.h"
81#include "DisplayHardware/HWComposer.h"
82#include "DisplayHardware/VirtualDisplaySurface.h"
83
84#include "Effects/Daltonizer.h"
85
86#include "RenderEngine/RenderEngine.h"
87#include <cutils/compiler.h>
88
89#define DISPLAY_COUNT 1
90
91/*
92 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
93 * black pixels.
94 */
95#define DEBUG_SCREENSHOTS false
96
97EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
98
Fabien Sanglard9d96de42016-10-11 00:15:18 +000099namespace android {
100
101// This is the phase offset in nanoseconds of the software vsync event
102// relative to the vsync event reported by HWComposer. The software vsync
103// event is when SurfaceFlinger and Choreographer-based applications run each
104// frame.
105//
106// This phase offset allows adjustment of the minimum latency from application
107// wake-up (by Choregographer) time to the time at which the resulting window
108// image is displayed. This value may be either positive (after the HW vsync)
109// or negative (before the HW vsync). Setting it to 0 will result in a
110// minimum latency of two vsync periods because the app and SurfaceFlinger
111// will run just after the HW vsync. Setting it to a positive number will
112// result in the minimum latency being:
113//
114// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
115//
116// Note that reducing this latency makes it more likely for the applications
117// to not have their window content image ready in time. When this happens
118// the latency will end up being an additional vsync period, and animations
119// will hiccup. Therefore, this latency should be tuned somewhat
120// conservatively (or at least with awareness of the trade-off being made).
121static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
122
123// This is the phase offset at which SurfaceFlinger's composition runs.
124static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
125
126// ---------------------------------------------------------------------------
127
128const String16 sHardwareTest("android.permission.HARDWARE_TEST");
129const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
130const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
131const String16 sDump("android.permission.DUMP");
132
133// ---------------------------------------------------------------------------
134
135SurfaceFlinger::SurfaceFlinger()
136 : BnSurfaceComposer(),
137 mTransactionFlags(0),
138 mTransactionPending(false),
139 mAnimTransactionPending(false),
140 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700141 mLayersAdded(false),
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000142 mRepaintEverything(0),
143 mRenderEngine(NULL),
144 mBootTime(systemTime()),
145 mVisibleRegionsDirty(false),
146 mHwWorkListDirty(false),
147 mAnimCompositionPending(false),
148 mDebugRegion(0),
149 mDebugDDMS(0),
150 mDebugDisableHWC(0),
151 mDebugDisableTransformHint(0),
152 mDebugInSwapBuffers(0),
153 mLastSwapBufferTime(0),
154 mDebugInTransaction(0),
155 mLastTransactionTime(0),
156 mBootFinished(false),
157 mForceFullDamage(false),
158 mInterceptor(),
159 mPrimaryDispSync("PrimaryDispSync"),
160 mPrimaryHWVsyncEnabled(false),
161 mHWVsyncAvailable(false),
162 mDaltonize(false),
163 mHasColorMatrix(false),
164 mHasPoweredOff(false),
165 mFrameBuckets(),
166 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700167 mLastSwapTime(0),
168 mNumLayers(0)
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000169{
170 ALOGI("SurfaceFlinger is starting");
171
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000172 char value[PROPERTY_VALUE_MAX];
173
174 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
175 mGpuToCpuSupported = !atoi(value);
176
177 property_get("debug.sf.showupdates", value, "0");
178 mDebugRegion = atoi(value);
179
180 property_get("debug.sf.ddms", value, "0");
181 mDebugDDMS = atoi(value);
182 if (mDebugDDMS) {
183 if (!startDdmConnection()) {
184 // start failed, and DDMS debugging not enabled
185 mDebugDDMS = 0;
186 }
187 }
188 ALOGI_IF(mDebugRegion, "showupdates enabled");
189 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
190
191 property_get("debug.sf.disable_hwc_vds", value, "0");
192 mUseHwcVirtualDisplays = !atoi(value);
193 ALOGI_IF(!mUseHwcVirtualDisplays, "Disabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800194
195 property_get("ro.sf.disable_triple_buffer", value, "0");
196 mLayerTripleBufferingDisabled = !atoi(value);
197 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000198}
199
200void SurfaceFlinger::onFirstRef()
201{
202 mEventQueue.init(this);
203}
204
205SurfaceFlinger::~SurfaceFlinger()
206{
207 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
208 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
209 eglTerminate(display);
210}
211
212void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
213{
214 // the window manager died on us. prepare its eulogy.
215
216 // restore initial conditions (default device unblank, etc)
217 initializeDisplays();
218
219 // restart the boot-animation
220 startBootAnim();
221}
222
Robert Carr1db73f62016-12-21 12:58:51 -0800223static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000224 status_t err = client->initCheck();
225 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800226 return client;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000227 }
Robert Carr1db73f62016-12-21 12:58:51 -0800228 return nullptr;
229}
230
231sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
232 return initClient(new Client(this));
233}
234
235sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
236 const sp<IGraphicBufferProducer>& gbp) {
237 if (authenticateSurfaceTexture(gbp) == false) {
238 return nullptr;
239 }
240 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
241 if (layer == nullptr) {
242 return nullptr;
243 }
244
245 return initClient(new Client(this, layer));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000246}
247
248sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
249 bool secure)
250{
251 class DisplayToken : public BBinder {
252 sp<SurfaceFlinger> flinger;
253 virtual ~DisplayToken() {
254 // no more references, this display must be terminated
255 Mutex::Autolock _l(flinger->mStateLock);
256 flinger->mCurrentState.displays.removeItem(this);
257 flinger->setTransactionFlags(eDisplayTransactionNeeded);
258 }
259 public:
260 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
261 : flinger(flinger) {
262 }
263 };
264
265 sp<BBinder> token = new DisplayToken(this);
266
267 Mutex::Autolock _l(mStateLock);
268 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
269 info.displayName = displayName;
270 mCurrentState.displays.add(token, info);
271 mInterceptor.saveDisplayCreation(info);
272 return token;
273}
274
275void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
276 Mutex::Autolock _l(mStateLock);
277
278 ssize_t idx = mCurrentState.displays.indexOfKey(display);
279 if (idx < 0) {
280 ALOGW("destroyDisplay: invalid display token");
281 return;
282 }
283
284 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
285 if (!info.isVirtualDisplay()) {
286 ALOGE("destroyDisplay called for non-virtual display");
287 return;
288 }
289 mInterceptor.saveDisplayDeletion(info.displayId);
290 mCurrentState.displays.removeItemsAt(idx);
291 setTransactionFlags(eDisplayTransactionNeeded);
292}
293
294void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
295 ALOGW_IF(mBuiltinDisplays[type],
296 "Overwriting display token for display type %d", type);
297 mBuiltinDisplays[type] = new BBinder();
298 // All non-virtual displays are currently considered secure.
299 DisplayDeviceState info(type, true);
300 mCurrentState.displays.add(mBuiltinDisplays[type], info);
301 mInterceptor.saveDisplayCreation(info);
302}
303
304sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
305 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
306 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
307 return NULL;
308 }
309 return mBuiltinDisplays[id];
310}
311
312sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
313{
314 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
315 return gba;
316}
317
318void SurfaceFlinger::bootFinished()
319{
Wei Wangb254fa32017-01-31 17:43:23 -0800320 if (mStartBootAnimThread->join() != NO_ERROR) {
321 ALOGE("Join StartBootAnimThread failed!");
322 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000323 const nsecs_t now = systemTime();
324 const nsecs_t duration = now - mBootTime;
325 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
326 mBootFinished = true;
327
328 // wait patiently for the window manager death
329 const String16 name("window");
330 sp<IBinder> window(defaultServiceManager()->getService(name));
331 if (window != 0) {
332 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
333 }
334
335 // stop boot animation
336 // formerly we would just kill the process, but we now ask it to exit so it
337 // can choose where to stop the animation.
338 property_set("service.bootanim.exit", "1");
339
340 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
341 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
342 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
343}
344
345void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
346 class MessageDestroyGLTexture : public MessageBase {
347 RenderEngine& engine;
348 uint32_t texture;
349 public:
350 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
351 : engine(engine), texture(texture) {
352 }
353 virtual bool handler() {
354 engine.deleteTextures(1, &texture);
355 return true;
356 }
357 };
358 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
359}
360
361class DispSyncSource : public VSyncSource, private DispSync::Callback {
362public:
363 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
364 const char* name) :
365 mName(name),
366 mValue(0),
367 mTraceVsync(traceVsync),
368 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
369 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
370 mDispSync(dispSync),
371 mCallbackMutex(),
372 mCallback(),
373 mVsyncMutex(),
374 mPhaseOffset(phaseOffset),
375 mEnabled(false) {}
376
377 virtual ~DispSyncSource() {}
378
379 virtual void setVSyncEnabled(bool enable) {
380 Mutex::Autolock lock(mVsyncMutex);
381 if (enable) {
382 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
383 static_cast<DispSync::Callback*>(this));
384 if (err != NO_ERROR) {
385 ALOGE("error registering vsync callback: %s (%d)",
386 strerror(-err), err);
387 }
388 //ATRACE_INT(mVsyncOnLabel.string(), 1);
389 } else {
390 status_t err = mDispSync->removeEventListener(
391 static_cast<DispSync::Callback*>(this));
392 if (err != NO_ERROR) {
393 ALOGE("error unregistering vsync callback: %s (%d)",
394 strerror(-err), err);
395 }
396 //ATRACE_INT(mVsyncOnLabel.string(), 0);
397 }
398 mEnabled = enable;
399 }
400
401 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
402 Mutex::Autolock lock(mCallbackMutex);
403 mCallback = callback;
404 }
405
406 virtual void setPhaseOffset(nsecs_t phaseOffset) {
407 Mutex::Autolock lock(mVsyncMutex);
408
409 // Normalize phaseOffset to [0, period)
410 auto period = mDispSync->getPeriod();
411 phaseOffset %= period;
412 if (phaseOffset < 0) {
413 // If we're here, then phaseOffset is in (-period, 0). After this
414 // operation, it will be in (0, period)
415 phaseOffset += period;
416 }
417 mPhaseOffset = phaseOffset;
418
419 // If we're not enabled, we don't need to mess with the listeners
420 if (!mEnabled) {
421 return;
422 }
423
424 // Remove the listener with the old offset
425 status_t err = mDispSync->removeEventListener(
426 static_cast<DispSync::Callback*>(this));
427 if (err != NO_ERROR) {
428 ALOGE("error unregistering vsync callback: %s (%d)",
429 strerror(-err), err);
430 }
431
432 // Add a listener with the new offset
433 err = mDispSync->addEventListener(mName, mPhaseOffset,
434 static_cast<DispSync::Callback*>(this));
435 if (err != NO_ERROR) {
436 ALOGE("error registering vsync callback: %s (%d)",
437 strerror(-err), err);
438 }
439 }
440
441private:
442 virtual void onDispSyncEvent(nsecs_t when) {
443 sp<VSyncSource::Callback> callback;
444 {
445 Mutex::Autolock lock(mCallbackMutex);
446 callback = mCallback;
447
448 if (mTraceVsync) {
449 mValue = (mValue + 1) % 2;
450 ATRACE_INT(mVsyncEventLabel.string(), mValue);
451 }
452 }
453
454 if (callback != NULL) {
455 callback->onVSyncEvent(when);
456 }
457 }
458
459 const char* const mName;
460
461 int mValue;
462
463 const bool mTraceVsync;
464 const String8 mVsyncOnLabel;
465 const String8 mVsyncEventLabel;
466
467 DispSync* mDispSync;
468
469 Mutex mCallbackMutex; // Protects the following
470 sp<VSyncSource::Callback> mCallback;
471
472 Mutex mVsyncMutex; // Protects the following
473 nsecs_t mPhaseOffset;
474 bool mEnabled;
475};
476
477class InjectVSyncSource : public VSyncSource {
478public:
479 InjectVSyncSource() {}
480
481 virtual ~InjectVSyncSource() {}
482
483 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
484 std::lock_guard<std::mutex> lock(mCallbackMutex);
485 mCallback = callback;
486 }
487
488 virtual void onInjectSyncEvent(nsecs_t when) {
489 std::lock_guard<std::mutex> lock(mCallbackMutex);
490 mCallback->onVSyncEvent(when);
491 }
492
493 virtual void setVSyncEnabled(bool) {}
494 virtual void setPhaseOffset(nsecs_t) {}
495
496private:
497 std::mutex mCallbackMutex; // Protects the following
498 sp<VSyncSource::Callback> mCallback;
499};
500
501void SurfaceFlinger::init() {
502 ALOGI( "SurfaceFlinger's main thread ready to run. "
503 "Initializing graphics H/W...");
504
505 Mutex::Autolock _l(mStateLock);
506
507 // initialize EGL for the default display
508 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
509 eglInitialize(mEGLDisplay, NULL, NULL);
510
511 // start the EventThread
512 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
513 vsyncPhaseOffsetNs, true, "app");
514 mEventThread = new EventThread(vsyncSrc, *this, false);
515 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
516 sfVsyncPhaseOffsetNs, true, "sf");
517 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
518 mEventQueue.setEventThread(mSFEventThread);
519
520 // set SFEventThread to SCHED_FIFO to minimize jitter
521 struct sched_param param = {0};
522 param.sched_priority = 2;
523 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
524 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
525 }
526
527
528 // Initialize the H/W composer object. There may or may not be an
529 // actual hardware composer underneath.
530 mHwc = new HWComposer(this,
531 *static_cast<HWComposer::EventHandler *>(this));
532
533 // get a RenderEngine for the given display / config (can't fail)
534 mRenderEngine = RenderEngine::create(mEGLDisplay, mHwc->getVisualID());
535
536 // retrieve the EGL context that was selected/created
537 mEGLContext = mRenderEngine->getEGLContext();
538
539 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
540 "couldn't create EGLContext");
541
542 // initialize our non-virtual displays
543 for (size_t i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
544 DisplayDevice::DisplayType type((DisplayDevice::DisplayType)i);
545 // set-up the displays that are already connected
546 if (mHwc->isConnected(i) || type==DisplayDevice::DISPLAY_PRIMARY) {
547 // All non-virtual displays are currently considered secure.
548 bool isSecure = true;
549 createBuiltinDisplayLocked(type);
550 wp<IBinder> token = mBuiltinDisplays[i];
551
552 sp<IGraphicBufferProducer> producer;
553 sp<IGraphicBufferConsumer> consumer;
554 BufferQueue::createBufferQueue(&producer, &consumer,
555 new GraphicBufferAlloc());
556
557 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, i,
558 consumer);
559 int32_t hwcId = allocateHwcDisplayId(type);
560 sp<DisplayDevice> hw = new DisplayDevice(this,
561 type, hwcId, mHwc->getFormat(hwcId), isSecure, token,
562 fbs, producer,
563 mRenderEngine->getEGLConfig());
564 if (i > DisplayDevice::DISPLAY_PRIMARY) {
565 // FIXME: currently we don't get blank/unblank requests
566 // for displays other than the main display, so we always
567 // assume a connected display is unblanked.
568 ALOGD("marking display %zu as acquired/unblanked", i);
569 hw->setPowerMode(HWC_POWER_MODE_NORMAL);
570 }
571 mDisplays.add(token, hw);
572 }
573 }
574
575 // make the GLContext current so that we can create textures when creating Layers
576 // (which may happens before we render something)
577 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
578
579 mEventControlThread = new EventControlThread(this);
580 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
581
582 // set a fake vsync period if there is no HWComposer
583 if (mHwc->initCheck() != NO_ERROR) {
584 mPrimaryDispSync.setPeriod(16666667);
585 }
586
587 // initialize our drawing state
588 mDrawingState = mCurrentState;
589
590 // set initial conditions (e.g. unblank default device)
591 initializeDisplays();
592
593 mRenderEngine->primeCache();
594
Wei Wangb254fa32017-01-31 17:43:23 -0800595 mStartBootAnimThread = new StartBootAnimThread();
596 if (mStartBootAnimThread->Start() != NO_ERROR) {
597 ALOGE("Run StartBootAnimThread failed!");
598 }
599
600 ALOGV("Done initializing");
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000601}
602
603int32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) {
604 return (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) ?
605 type : mHwc->allocateDisplayId();
606}
607
608void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800609 // Start boot animation service by setting a property mailbox
610 // if property setting thread is already running, Start() will be just a NOP
611 mStartBootAnimThread->Start();
612 // Wait until property was set
613 if (mStartBootAnimThread->join() != NO_ERROR) {
614 ALOGE("Join StartBootAnimThread failed!");
615 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000616}
617
618size_t SurfaceFlinger::getMaxTextureSize() const {
619 return mRenderEngine->getMaxTextureSize();
620}
621
622size_t SurfaceFlinger::getMaxViewportDims() const {
623 return mRenderEngine->getMaxViewportDims();
624}
625
626// ----------------------------------------------------------------------------
627
628bool SurfaceFlinger::authenticateSurfaceTexture(
629 const sp<IGraphicBufferProducer>& bufferProducer) const {
630 Mutex::Autolock _l(mStateLock);
631 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
632 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
633}
634
Brian Anderson069b3652016-07-22 10:32:47 -0700635status_t SurfaceFlinger::getSupportedFrameTimestamps(
Brian Anderson3890c392016-07-25 12:48:08 -0700636 std::vector<FrameEvent>* outSupported) const {
Brian Anderson069b3652016-07-22 10:32:47 -0700637 *outSupported = {
Brian Anderson3890c392016-07-25 12:48:08 -0700638 FrameEvent::REQUESTED_PRESENT,
639 FrameEvent::ACQUIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700640 FrameEvent::LATCH,
Brian Anderson3890c392016-07-25 12:48:08 -0700641 FrameEvent::FIRST_REFRESH_START,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700642 FrameEvent::LAST_REFRESH_START,
Brian Anderson3890c392016-07-25 12:48:08 -0700643 FrameEvent::GL_COMPOSITION_DONE,
644 FrameEvent::DISPLAY_RETIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700645 FrameEvent::DEQUEUE_READY,
Brian Anderson3890c392016-07-25 12:48:08 -0700646 FrameEvent::RELEASE,
Brian Anderson069b3652016-07-22 10:32:47 -0700647 };
648 return NO_ERROR;
649}
650
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000651status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
652 Vector<DisplayInfo>* configs) {
653 if ((configs == NULL) || (display.get() == NULL)) {
654 return BAD_VALUE;
655 }
656
657 int32_t type = getDisplayType(display);
658 if (type < 0) return type;
659
660 // TODO: Not sure if display density should handled by SF any longer
661 class Density {
662 static int getDensityFromProperty(char const* propName) {
663 char property[PROPERTY_VALUE_MAX];
664 int density = 0;
665 if (property_get(propName, property, NULL) > 0) {
666 density = atoi(property);
667 }
668 return density;
669 }
670 public:
671 static int getEmuDensity() {
672 return getDensityFromProperty("qemu.sf.lcd_density"); }
673 static int getBuildDensity() {
674 return getDensityFromProperty("ro.sf.lcd_density"); }
675 };
676
677 configs->clear();
678
679 const Vector<HWComposer::DisplayConfig>& hwConfigs =
680 getHwComposer().getConfigs(type);
681 for (size_t c = 0; c < hwConfigs.size(); ++c) {
682 const HWComposer::DisplayConfig& hwConfig = hwConfigs[c];
683 DisplayInfo info = DisplayInfo();
684
685 float xdpi = hwConfig.xdpi;
686 float ydpi = hwConfig.ydpi;
687
688 if (type == DisplayDevice::DISPLAY_PRIMARY) {
689 // The density of the device is provided by a build property
690 float density = Density::getBuildDensity() / 160.0f;
691 if (density == 0) {
692 // the build doesn't provide a density -- this is wrong!
693 // use xdpi instead
694 ALOGE("ro.sf.lcd_density must be defined as a build property");
695 density = xdpi / 160.0f;
696 }
697 if (Density::getEmuDensity()) {
698 // if "qemu.sf.lcd_density" is specified, it overrides everything
699 xdpi = ydpi = density = Density::getEmuDensity();
700 density /= 160.0f;
701 }
702 info.density = density;
703
704 // TODO: this needs to go away (currently needed only by webkit)
705 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
706 info.orientation = hw->getOrientation();
707 } else {
708 // TODO: where should this value come from?
709 static const int TV_DENSITY = 213;
710 info.density = TV_DENSITY / 160.0f;
711 info.orientation = 0;
712 }
713
714 info.w = hwConfig.width;
715 info.h = hwConfig.height;
716 info.xdpi = xdpi;
717 info.ydpi = ydpi;
718 info.fps = float(1e9 / hwConfig.refresh);
719 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
720
721 // This is how far in advance a buffer must be queued for
722 // presentation at a given time. If you want a buffer to appear
723 // on the screen at time N, you must submit the buffer before
724 // (N - presentationDeadline).
725 //
726 // Normally it's one full refresh period (to give SF a chance to
727 // latch the buffer), but this can be reduced by configuring a
728 // DispSync offset. Any additional delays introduced by the hardware
729 // composer or panel must be accounted for here.
730 //
731 // We add an additional 1ms to allow for processing time and
732 // differences between the ideal and actual refresh rate.
733 info.presentationDeadline =
734 hwConfig.refresh - SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
735
736 // All non-virtual displays are currently considered secure.
737 info.secure = true;
738
739 configs->push_back(info);
740 }
741
742 return NO_ERROR;
743}
744
745status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
746 DisplayStatInfo* stats) {
747 if (stats == NULL) {
748 return BAD_VALUE;
749 }
750
751 // FIXME for now we always return stats for the primary display
752 memset(stats, 0, sizeof(*stats));
753 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
754 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
755 return NO_ERROR;
756}
757
758int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
759 sp<DisplayDevice> device(getDisplayDevice(display));
760 if (device != NULL) {
761 return device->getActiveConfig();
762 }
763 return BAD_VALUE;
764}
765
766void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
767 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
768 this);
769 int32_t type = hw->getDisplayType();
770 int currentMode = hw->getActiveConfig();
771
772 if (mode == currentMode) {
773 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
774 return;
775 }
776
777 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
778 ALOGW("Trying to set config for virtual display");
779 return;
780 }
781
782 hw->setActiveConfig(mode);
783 getHwComposer().setActiveConfig(type, mode);
784}
785
786status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
787 class MessageSetActiveConfig: public MessageBase {
788 SurfaceFlinger& mFlinger;
789 sp<IBinder> mDisplay;
790 int mMode;
791 public:
792 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
793 int mode) :
794 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
795 virtual bool handler() {
796 Vector<DisplayInfo> configs;
797 mFlinger.getDisplayConfigs(mDisplay, &configs);
798 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
799 ALOGE("Attempt to set active config = %d for display with %zu configs",
800 mMode, configs.size());
801 }
802 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
803 if (hw == NULL) {
804 ALOGE("Attempt to set active config = %d for null display %p",
805 mMode, mDisplay.get());
806 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
807 ALOGW("Attempt to set active config = %d for virtual display",
808 mMode);
809 } else {
810 mFlinger.setActiveConfigInternal(hw, mMode);
811 }
812 return true;
813 }
814 };
815 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
816 postMessageSync(msg);
817 return NO_ERROR;
818}
819
820status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
821 Vector<android_color_mode_t>* outColorModes) {
822 if (outColorModes == nullptr || display.get() == nullptr) {
823 return BAD_VALUE;
824 }
825
826 int32_t type = getDisplayType(display);
827 if (type < 0) return type;
828
829 std::set<android_color_mode_t> colorModes;
830 for (const HWComposer::DisplayConfig& hwConfig : getHwComposer().getConfigs(type)) {
831 colorModes.insert(hwConfig.colorMode);
832 }
833
834 outColorModes->clear();
835 std::copy(colorModes.cbegin(), colorModes.cend(), std::back_inserter(*outColorModes));
836
837 return NO_ERROR;
838}
839
840android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
841 if (display.get() == nullptr) return static_cast<android_color_mode_t>(BAD_VALUE);
842
843 int32_t type = getDisplayType(display);
844 if (type < 0) return static_cast<android_color_mode_t>(type);
845
846 return getHwComposer().getColorMode(type);
847}
848
849status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
850 android_color_mode_t colorMode) {
851 if (display.get() == nullptr || colorMode < 0) {
852 return BAD_VALUE;
853 }
854
855 int32_t type = getDisplayType(display);
856 if (type < 0) return type;
857 const Vector<HWComposer::DisplayConfig>& hwConfigs = getHwComposer().getConfigs(type);
858 HWComposer::DisplayConfig desiredConfig = hwConfigs[getHwComposer().getCurrentConfig(type)];
859 desiredConfig.colorMode = colorMode;
860 for (size_t c = 0; c < hwConfigs.size(); ++c) {
861 const HWComposer::DisplayConfig config = hwConfigs[c];
862 if (config == desiredConfig) {
863 return setActiveConfig(display, c);
864 }
865 }
866 return BAD_VALUE;
867}
868
869status_t SurfaceFlinger::clearAnimationFrameStats() {
870 Mutex::Autolock _l(mStateLock);
871 mAnimFrameTracker.clearStats();
872 return NO_ERROR;
873}
874
875status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
876 Mutex::Autolock _l(mStateLock);
877 mAnimFrameTracker.getStats(outStats);
878 return NO_ERROR;
879}
880
881status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& /*display*/,
882 HdrCapabilities* outCapabilities) const {
883 // HWC1 does not provide HDR capabilities
884 *outCapabilities = HdrCapabilities();
885 return NO_ERROR;
886}
887
888status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
889 if (enable == mInjectVSyncs) {
890 return NO_ERROR;
891 }
892
893 if (enable) {
894 mInjectVSyncs = enable;
895 ALOGV("VSync Injections enabled");
896 if (mVSyncInjector.get() == nullptr) {
897 mVSyncInjector = new InjectVSyncSource();
898 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
899 }
900 mEventQueue.setEventThread(mInjectorEventThread);
901 } else {
902 mInjectVSyncs = enable;
903 ALOGV("VSync Injections disabled");
904 mEventQueue.setEventThread(mSFEventThread);
905 mVSyncInjector.clear();
906 }
907 return NO_ERROR;
908}
909
910status_t SurfaceFlinger::injectVSync(nsecs_t when) {
911 if (!mInjectVSyncs) {
912 ALOGE("VSync Injections not enabled");
913 return BAD_VALUE;
914 }
915 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
916 ALOGV("Injecting VSync inside SurfaceFlinger");
917 mVSyncInjector->onInjectSyncEvent(when);
918 }
919 return NO_ERROR;
920}
921
922// ----------------------------------------------------------------------------
923
924sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
925 return mEventThread->createEventConnection();
926}
927
928// ----------------------------------------------------------------------------
929
930void SurfaceFlinger::waitForEvent() {
931 mEventQueue.waitMessage();
932}
933
934void SurfaceFlinger::signalTransaction() {
935 mEventQueue.invalidate();
936}
937
938void SurfaceFlinger::signalLayerUpdate() {
939 mEventQueue.invalidate();
940}
941
942void SurfaceFlinger::signalRefresh() {
943 mEventQueue.refresh();
944}
945
946status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
947 nsecs_t reltime, uint32_t /* flags */) {
948 return mEventQueue.postMessage(msg, reltime);
949}
950
951status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
952 nsecs_t reltime, uint32_t /* flags */) {
953 status_t res = mEventQueue.postMessage(msg, reltime);
954 if (res == NO_ERROR) {
955 msg->wait();
956 }
957 return res;
958}
959
960void SurfaceFlinger::run() {
961 do {
962 waitForEvent();
963 } while (true);
964}
965
966void SurfaceFlinger::enableHardwareVsync() {
967 Mutex::Autolock _l(mHWVsyncLock);
968 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
969 mPrimaryDispSync.beginResync();
970 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
971 mEventControlThread->setVsyncEnabled(true);
972 mPrimaryHWVsyncEnabled = true;
973 }
974}
975
976void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
977 Mutex::Autolock _l(mHWVsyncLock);
978
979 if (makeAvailable) {
980 mHWVsyncAvailable = true;
981 } else if (!mHWVsyncAvailable) {
982 // Hardware vsync is not currently available, so abort the resync
983 // attempt for now
984 return;
985 }
986
987 const nsecs_t period =
988 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
989
990 mPrimaryDispSync.reset();
991 mPrimaryDispSync.setPeriod(period);
992
993 if (!mPrimaryHWVsyncEnabled) {
994 mPrimaryDispSync.beginResync();
995 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
996 mEventControlThread->setVsyncEnabled(true);
997 mPrimaryHWVsyncEnabled = true;
998 }
999}
1000
1001void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
1002 Mutex::Autolock _l(mHWVsyncLock);
1003 if (mPrimaryHWVsyncEnabled) {
1004 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1005 mEventControlThread->setVsyncEnabled(false);
1006 mPrimaryDispSync.endResync();
1007 mPrimaryHWVsyncEnabled = false;
1008 }
1009 if (makeUnavailable) {
1010 mHWVsyncAvailable = false;
1011 }
1012}
1013
1014void SurfaceFlinger::resyncWithRateLimit() {
1015 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1016 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
1017 resyncToHardwareVsync(false);
1018 }
1019}
1020
1021void SurfaceFlinger::onVSyncReceived(int type, nsecs_t timestamp) {
1022 bool needsHwVsync = false;
1023
1024 { // Scope for the lock
1025 Mutex::Autolock _l(mHWVsyncLock);
1026 if (type == 0 && mPrimaryHWVsyncEnabled) {
1027 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
1028 }
1029 }
1030
1031 if (needsHwVsync) {
1032 enableHardwareVsync();
1033 } else {
1034 disableHardwareVsync(false);
1035 }
1036}
1037
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001038void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
1039 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1040 *compositorTiming = mCompositorTiming;
1041}
1042
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001043void SurfaceFlinger::onHotplugReceived(int type, bool connected) {
1044 if (mEventThread == NULL) {
1045 // This is a temporary workaround for b/7145521. A non-null pointer
1046 // does not mean EventThread has finished initializing, so this
1047 // is not a correct fix.
1048 ALOGW("WARNING: EventThread not started, ignoring hotplug");
1049 return;
1050 }
1051
1052 if (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1053 Mutex::Autolock _l(mStateLock);
1054 if (connected) {
1055 createBuiltinDisplayLocked((DisplayDevice::DisplayType)type);
1056 } else {
1057 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1058 mBuiltinDisplays[type].clear();
1059 }
1060 setTransactionFlags(eDisplayTransactionNeeded);
1061
1062 // Defer EventThread notification until SF has updated mDisplays.
1063 }
1064}
1065
1066void SurfaceFlinger::eventControl(int disp, int event, int enabled) {
1067 ATRACE_CALL();
1068 getHwComposer().eventControl(disp, event, enabled);
1069}
1070
1071void SurfaceFlinger::onMessageReceived(int32_t what) {
1072 ATRACE_CALL();
1073 switch (what) {
1074 case MessageQueue::INVALIDATE: {
1075 bool refreshNeeded = handleMessageTransaction();
1076 refreshNeeded |= handleMessageInvalidate();
1077 refreshNeeded |= mRepaintEverything;
1078 if (refreshNeeded) {
1079 // Signal a refresh if a transaction modified the window state,
1080 // a new buffer was latched, or if HWC has requested a full
1081 // repaint
1082 signalRefresh();
1083 }
1084 break;
1085 }
1086 case MessageQueue::REFRESH: {
1087 handleMessageRefresh();
1088 break;
1089 }
1090 }
1091}
1092
1093bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001094 uint32_t transactionFlags = peekTransactionFlags();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001095 if (transactionFlags) {
1096 handleTransaction(transactionFlags);
1097 return true;
1098 }
1099 return false;
1100}
1101
1102bool SurfaceFlinger::handleMessageInvalidate() {
1103 ATRACE_CALL();
1104 return handlePageFlip();
1105}
1106
1107void SurfaceFlinger::handleMessageRefresh() {
1108 ATRACE_CALL();
1109
1110 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1111
Brian Andersond6927fb2016-07-23 23:37:30 -07001112 preComposition(refreshStartTime);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001113 rebuildLayerStacks();
1114 setUpHWComposer();
1115 doDebugFlashRegions();
1116 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001117 postComposition(refreshStartTime);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001118}
1119
1120void SurfaceFlinger::doDebugFlashRegions()
1121{
1122 // is debugging enabled
1123 if (CC_LIKELY(!mDebugRegion))
1124 return;
1125
1126 const bool repaintEverything = mRepaintEverything;
1127 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1128 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1129 if (hw->isDisplayOn()) {
1130 // transform the dirty region into this screen's coordinate space
1131 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1132 if (!dirtyRegion.isEmpty()) {
1133 // redraw the whole screen
1134 doComposeSurfaces(hw, Region(hw->bounds()));
1135
1136 // and draw the dirty region
1137 const int32_t height = hw->getHeight();
1138 RenderEngine& engine(getRenderEngine());
1139 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1140
1141 hw->compositionComplete();
1142 hw->swapBuffers(getHwComposer());
1143 }
1144 }
1145 }
1146
1147 postFramebuffer();
1148
1149 if (mDebugRegion > 1) {
1150 usleep(mDebugRegion * 1000);
1151 }
1152
1153 HWComposer& hwc(getHwComposer());
1154 if (hwc.initCheck() == NO_ERROR) {
1155 status_t err = hwc.prepare();
1156 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1157 }
1158}
1159
Brian Andersond6927fb2016-07-23 23:37:30 -07001160void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001161{
1162 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001163 mDrawingState.traverseInZOrder([&](Layer* layer) {
1164 if (layer->onPreComposition(refreshStartTime)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001165 needExtraInvalidate = true;
1166 }
Robert Carr2047fae2016-11-28 14:09:09 -08001167 });
1168
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001169 if (needExtraInvalidate) {
1170 signalLayerUpdate();
1171 }
1172}
1173
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001174void SurfaceFlinger::updateCompositorTiming(
1175 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1176 std::shared_ptr<FenceTime>& presentFenceTime) {
1177 // Update queue of past composite+present times and determine the
1178 // most recently known composite to present latency.
1179 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1180 nsecs_t compositeToPresentLatency = -1;
1181 while (!mCompositePresentTimes.empty()) {
1182 CompositePresentTime& cpt = mCompositePresentTimes.front();
1183 // Cached values should have been updated before calling this method,
1184 // which helps avoid duplicate syscalls.
1185 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1186 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1187 break;
1188 }
1189 compositeToPresentLatency = displayTime - cpt.composite;
1190 mCompositePresentTimes.pop();
1191 }
1192
1193 // Don't let mCompositePresentTimes grow unbounded, just in case.
1194 while (mCompositePresentTimes.size() > 16) {
1195 mCompositePresentTimes.pop();
1196 }
1197
1198 // Integer division and modulo round toward 0 not -inf, so we need to
1199 // treat negative and positive offsets differently.
1200 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs >= 0) ?
1201 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1202 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1203
1204 // Snap the latency to a value that removes scheduling jitter from the
1205 // composition and present times, which often have >1ms of jitter.
1206 // Reducing jitter is important if an app attempts to extrapolate
1207 // something (such as user input) to an accurate diasplay time.
1208 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1209 // with (presentLatency % interval).
1210 nsecs_t snappedCompositeToPresentLatency = -1;
1211 if (compositeToPresentLatency >= 0) {
1212 nsecs_t bias = vsyncInterval / 2;
1213 int64_t extraVsyncs =
1214 (compositeToPresentLatency - idealLatency + bias) /
1215 vsyncInterval;
1216 nsecs_t extraLatency = extraVsyncs * vsyncInterval;
1217 snappedCompositeToPresentLatency = idealLatency + extraLatency;
1218 }
1219
1220 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1221 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1222 mCompositorTiming.interval = vsyncInterval;
1223 if (snappedCompositeToPresentLatency >= 0) {
1224 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
1225 }
1226}
1227
1228void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001229{
Brian Andersond6927fb2016-07-23 23:37:30 -07001230 const HWComposer& hwc = getHwComposer();
1231 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
1232
Brian Anderson3d4039d2016-09-23 16:31:30 -07001233 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1234 if (getHwComposer().hasGlesComposition(hw->getHwcDisplayId())) {
1235 glCompositionDoneFenceTime =
1236 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1237 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1238 } else {
1239 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1240 }
1241 mGlCompositionDoneTimeline.updateSignalTimes();
1242
1243 sp<Fence> displayFence = mHwc->getDisplayFence(HWC_DISPLAY_PRIMARY);
1244 const std::shared_ptr<FenceTime>& presentFenceTime = FenceTime::NO_FENCE;
1245 auto retireFenceTime = std::make_shared<FenceTime>(displayFence);
1246 mDisplayTimeline.push(retireFenceTime);
1247 mDisplayTimeline.updateSignalTimes();
Brian Andersond6927fb2016-07-23 23:37:30 -07001248
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001249 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1250 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1251
1252 // We use the refreshStartTime which might be sampled a little later than
1253 // when we started doing work for this frame, but that should be okay
1254 // since updateCompositorTiming has snapping logic.
1255 updateCompositorTiming(
1256 vsyncPhase, vsyncInterval, refreshStartTime, retireFenceTime);
1257
Robert Carr2047fae2016-11-28 14:09:09 -08001258 mDrawingState.traverseInZOrder([&](Layer* layer) {
1259 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001260 presentFenceTime, retireFenceTime, mCompositorTiming);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001261 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001262 recordBufferingStats(layer->getName().string(),
1263 layer->getOccupancyHistory(false));
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001264 }
Robert Carr2047fae2016-11-28 14:09:09 -08001265 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001266
Brian Anderson3d4039d2016-09-23 16:31:30 -07001267 if (displayFence->isValid()) {
1268 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001269 enableHardwareVsync();
1270 } else {
1271 disableHardwareVsync(false);
1272 }
1273 }
1274
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001275 if (kIgnorePresentFences) {
1276 if (hw->isDisplayOn()) {
1277 enableHardwareVsync();
1278 }
1279 }
1280
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001281 if (mAnimCompositionPending) {
1282 mAnimCompositionPending = false;
1283
Brian Anderson3d4039d2016-09-23 16:31:30 -07001284 if (retireFenceTime->isValid()) {
1285 mAnimFrameTracker.setActualPresentFence(std::move(retireFenceTime));
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001286 } else {
1287 // The HWC doesn't support present fences, so use the refresh
1288 // timestamp instead.
1289 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
1290 mAnimFrameTracker.setActualPresentTime(presentTime);
1291 }
1292 mAnimFrameTracker.advanceFrame();
1293 }
1294
1295 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1296 return;
1297 }
1298
1299 nsecs_t currentTime = systemTime();
1300 if (mHasPoweredOff) {
1301 mHasPoweredOff = false;
1302 } else {
1303 nsecs_t period = mPrimaryDispSync.getPeriod();
1304 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1305 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1306 if (numPeriods < NUM_BUCKETS - 1) {
1307 mFrameBuckets[numPeriods] += elapsedTime;
1308 } else {
1309 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1310 }
1311 mTotalTime += elapsedTime;
1312 }
1313 mLastSwapTime = currentTime;
1314}
1315
1316void SurfaceFlinger::rebuildLayerStacks() {
1317 // rebuild the visible layer list per screen
1318 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1319 ATRACE_CALL();
1320 mVisibleRegionsDirty = false;
1321 invalidateHwcGeometry();
1322
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001323 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1324 Region opaqueRegion;
1325 Region dirtyRegion;
1326 Vector< sp<Layer> > layersSortedByZ;
1327 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1328 const Transform& tr(hw->getTransform());
1329 const Rect bounds(hw->getBounds());
1330 if (hw->isDisplayOn()) {
Robert Carr2047fae2016-11-28 14:09:09 -08001331 computeVisibleRegions(hw->getLayerStack(), dirtyRegion,
1332 opaqueRegion);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001333
Robert Carr2047fae2016-11-28 14:09:09 -08001334 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001335 if (layer->getLayerStack() == hw->getLayerStack()) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001336 Region drawRegion(tr.transform(
1337 layer->visibleNonTransparentRegion));
1338 drawRegion.andSelf(bounds);
1339 if (!drawRegion.isEmpty()) {
1340 layersSortedByZ.add(layer);
1341 }
1342 }
Robert Carr2047fae2016-11-28 14:09:09 -08001343 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001344 }
1345 hw->setVisibleLayersSortedByZ(layersSortedByZ);
1346 hw->undefinedRegion.set(bounds);
1347 hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1348 hw->dirtyRegion.orSelf(dirtyRegion);
1349 }
1350 }
1351}
1352
1353void SurfaceFlinger::setUpHWComposer() {
1354 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1355 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1356 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1357 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1358
1359 // If nothing has changed (!dirty), don't recompose.
1360 // If something changed, but we don't currently have any visible layers,
1361 // and didn't when we last did a composition, then skip it this time.
1362 // The second rule does two things:
1363 // - When all layers are removed from a display, we'll emit one black
1364 // frame, then nothing more until we get new layers.
1365 // - When a display is created with a private layer stack, we won't
1366 // emit any black frames until a layer is added to the layer stack.
1367 bool mustRecompose = dirty && !(empty && wasEmpty);
1368
1369 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1370 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1371 mustRecompose ? "doing" : "skipping",
1372 dirty ? "+" : "-",
1373 empty ? "+" : "-",
1374 wasEmpty ? "+" : "-");
1375
1376 mDisplays[dpy]->beginFrame(mustRecompose);
1377
1378 if (mustRecompose) {
1379 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1380 }
1381 }
1382
1383 HWComposer& hwc(getHwComposer());
1384 if (hwc.initCheck() == NO_ERROR) {
1385 // build the h/w work list
1386 if (CC_UNLIKELY(mHwWorkListDirty)) {
1387 mHwWorkListDirty = false;
1388 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1389 sp<const DisplayDevice> hw(mDisplays[dpy]);
1390 const int32_t id = hw->getHwcDisplayId();
1391 if (id >= 0) {
1392 const Vector< sp<Layer> >& currentLayers(
1393 hw->getVisibleLayersSortedByZ());
1394 const size_t count = currentLayers.size();
1395 if (hwc.createWorkList(id, count) == NO_ERROR) {
1396 HWComposer::LayerListIterator cur = hwc.begin(id);
1397 const HWComposer::LayerListIterator end = hwc.end(id);
1398 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1399 const sp<Layer>& layer(currentLayers[i]);
1400 layer->setGeometry(hw, *cur);
1401 if (mDebugDisableHWC || mDebugRegion || mDaltonize || mHasColorMatrix) {
1402 cur->setSkip(true);
1403 }
1404 }
1405 }
1406 }
1407 }
1408 }
1409
1410 // set the per-frame data
1411 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1412 sp<const DisplayDevice> hw(mDisplays[dpy]);
1413 const int32_t id = hw->getHwcDisplayId();
1414 if (id >= 0) {
1415 const Vector< sp<Layer> >& currentLayers(
1416 hw->getVisibleLayersSortedByZ());
1417 const size_t count = currentLayers.size();
1418 HWComposer::LayerListIterator cur = hwc.begin(id);
1419 const HWComposer::LayerListIterator end = hwc.end(id);
1420 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1421 /*
1422 * update the per-frame h/w composer data for each layer
1423 * and build the transparent region of the FB
1424 */
1425 const sp<Layer>& layer(currentLayers[i]);
1426 layer->setPerFrameData(hw, *cur);
1427 }
1428 }
1429 }
1430
1431 // If possible, attempt to use the cursor overlay on each display.
1432 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1433 sp<const DisplayDevice> hw(mDisplays[dpy]);
1434 const int32_t id = hw->getHwcDisplayId();
1435 if (id >= 0) {
1436 const Vector< sp<Layer> >& currentLayers(
1437 hw->getVisibleLayersSortedByZ());
1438 const size_t count = currentLayers.size();
1439 HWComposer::LayerListIterator cur = hwc.begin(id);
1440 const HWComposer::LayerListIterator end = hwc.end(id);
1441 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1442 const sp<Layer>& layer(currentLayers[i]);
1443 if (layer->isPotentialCursor()) {
1444 cur->setIsCursorLayerHint();
1445 break;
1446 }
1447 }
1448 }
1449 }
1450
1451 status_t err = hwc.prepare();
1452 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1453
1454 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1455 sp<const DisplayDevice> hw(mDisplays[dpy]);
1456 hw->prepareFrame(hwc);
1457 }
1458 }
1459}
1460
1461void SurfaceFlinger::doComposition() {
1462 ATRACE_CALL();
1463 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
1464 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1465 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1466 if (hw->isDisplayOn()) {
1467 // transform the dirty region into this screen's coordinate space
1468 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1469
1470 // repaint the framebuffer (if needed)
1471 doDisplayComposition(hw, dirtyRegion);
1472
1473 hw->dirtyRegion.clear();
1474 hw->flip(hw->swapRegion);
1475 hw->swapRegion.clear();
1476 }
1477 // inform the h/w that we're done compositing
1478 hw->compositionComplete();
1479 }
1480 postFramebuffer();
1481}
1482
1483void SurfaceFlinger::postFramebuffer()
1484{
1485 ATRACE_CALL();
1486
1487 const nsecs_t now = systemTime();
1488 mDebugInSwapBuffers = now;
1489
1490 HWComposer& hwc(getHwComposer());
1491 if (hwc.initCheck() == NO_ERROR) {
1492 if (!hwc.supportsFramebufferTarget()) {
1493 // EGL spec says:
1494 // "surface must be bound to the calling thread's current context,
1495 // for the current rendering API."
1496 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1497 }
1498 hwc.commit();
1499 }
1500
1501 // make the default display current because the VirtualDisplayDevice code cannot
1502 // deal with dequeueBuffer() being called outside of the composition loop; however
1503 // the code below can call glFlush() which is allowed (and does in some case) call
1504 // dequeueBuffer().
1505 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1506
1507 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1508 sp<const DisplayDevice> hw(mDisplays[dpy]);
1509 const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ());
1510 hw->onSwapBuffersCompleted(hwc);
1511 const size_t count = currentLayers.size();
1512 int32_t id = hw->getHwcDisplayId();
1513 if (id >=0 && hwc.initCheck() == NO_ERROR) {
1514 HWComposer::LayerListIterator cur = hwc.begin(id);
1515 const HWComposer::LayerListIterator end = hwc.end(id);
1516 for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
1517 currentLayers[i]->onLayerDisplayed(hw, &*cur);
1518 }
1519 } else {
1520 for (size_t i = 0; i < count; i++) {
1521 currentLayers[i]->onLayerDisplayed(hw, NULL);
1522 }
1523 }
1524 }
1525
1526 mLastSwapBufferTime = systemTime() - now;
1527 mDebugInSwapBuffers = 0;
1528
1529 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1530 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1531 logFrameStats();
1532 }
1533}
1534
1535void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
1536{
1537 ATRACE_CALL();
1538
1539 // here we keep a copy of the drawing state (that is the state that's
1540 // going to be overwritten by handleTransactionLocked()) outside of
1541 // mStateLock so that the side-effects of the State assignment
1542 // don't happen with mStateLock held (which can cause deadlocks).
1543 State drawingState(mDrawingState);
1544
1545 Mutex::Autolock _l(mStateLock);
1546 const nsecs_t now = systemTime();
1547 mDebugInTransaction = now;
1548
1549 // Here we're guaranteed that some transaction flags are set
1550 // so we can call handleTransactionLocked() unconditionally.
1551 // We call getTransactionFlags(), which will also clear the flags,
1552 // with mStateLock held to guarantee that mCurrentState won't change
1553 // until the transaction is committed.
1554
1555 transactionFlags = getTransactionFlags(eTransactionMask);
1556 handleTransactionLocked(transactionFlags);
1557
1558 mLastTransactionTime = systemTime() - now;
1559 mDebugInTransaction = 0;
1560 invalidateHwcGeometry();
1561 // here the transaction has been committed
1562}
1563
1564void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
1565{
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001566 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001567 mCurrentState.traverseInZOrder([](Layer* layer) {
1568 layer->notifyAvailableFrames();
1569 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001570
1571 /*
1572 * Traversal of the children
1573 * (perform the transaction for each of them if needed)
1574 */
1575
1576 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001577 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001578 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001579 if (!trFlags) return;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001580
1581 const uint32_t flags = layer->doTransaction(0);
1582 if (flags & Layer::eVisibleRegion)
1583 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001584 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001585 }
1586
1587 /*
1588 * Perform display own transactions if needed
1589 */
1590
1591 if (transactionFlags & eDisplayTransactionNeeded) {
1592 // here we take advantage of Vector's copy-on-write semantics to
1593 // improve performance by skipping the transaction entirely when
1594 // know that the lists are identical
1595 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1596 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
1597 if (!curr.isIdenticalTo(draw)) {
1598 mVisibleRegionsDirty = true;
1599 const size_t cc = curr.size();
1600 size_t dc = draw.size();
1601
1602 // find the displays that were removed
1603 // (ie: in drawing state but not in current state)
1604 // also handle displays that changed
1605 // (ie: displays that are in both lists)
1606 for (size_t i=0 ; i<dc ; i++) {
1607 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1608 if (j < 0) {
1609 // in drawing state but not in current state
1610 if (!draw[i].isMainDisplay()) {
1611 // Call makeCurrent() on the primary display so we can
1612 // be sure that nothing associated with this display
1613 // is current.
1614 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
1615 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
1616 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1617 if (hw != NULL)
1618 hw->disconnect(getHwComposer());
1619 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
1620 mEventThread->onHotplugReceived(draw[i].type, false);
1621 mDisplays.removeItem(draw.keyAt(i));
1622 } else {
1623 ALOGW("trying to remove the main display");
1624 }
1625 } else {
1626 // this display is in both lists. see if something changed.
1627 const DisplayDeviceState& state(curr[j]);
1628 const wp<IBinder>& display(curr.keyAt(j));
1629 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1630 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
1631 if (state_binder != draw_binder) {
1632 // changing the surface is like destroying and
1633 // recreating the DisplayDevice, so we just remove it
1634 // from the drawing state, so that it get re-added
1635 // below.
1636 sp<DisplayDevice> hw(getDisplayDevice(display));
1637 if (hw != NULL)
1638 hw->disconnect(getHwComposer());
1639 mDisplays.removeItem(display);
1640 mDrawingState.displays.removeItemsAt(i);
1641 dc--; i--;
1642 // at this point we must loop to the next item
1643 continue;
1644 }
1645
1646 const sp<DisplayDevice> disp(getDisplayDevice(display));
1647 if (disp != NULL) {
1648 if (state.layerStack != draw[i].layerStack) {
1649 disp->setLayerStack(state.layerStack);
1650 }
1651 if ((state.orientation != draw[i].orientation)
1652 || (state.viewport != draw[i].viewport)
1653 || (state.frame != draw[i].frame))
1654 {
1655 disp->setProjection(state.orientation,
1656 state.viewport, state.frame);
1657 }
1658 if (state.width != draw[i].width || state.height != draw[i].height) {
1659 disp->setDisplaySize(state.width, state.height);
1660 }
1661 }
1662 }
1663 }
1664
1665 // find displays that were added
1666 // (ie: in current state but not in drawing state)
1667 for (size_t i=0 ; i<cc ; i++) {
1668 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
1669 const DisplayDeviceState& state(curr[i]);
1670
1671 sp<DisplaySurface> dispSurface;
1672 sp<IGraphicBufferProducer> producer;
1673 sp<IGraphicBufferProducer> bqProducer;
1674 sp<IGraphicBufferConsumer> bqConsumer;
1675 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1676 new GraphicBufferAlloc());
1677
1678 int32_t hwcDisplayId = -1;
1679 if (state.isVirtualDisplay()) {
1680 // Virtual displays without a surface are dormant:
1681 // they have external state (layer stack, projection,
1682 // etc.) but no internal state (i.e. a DisplayDevice).
1683 if (state.surface != NULL) {
1684
1685 int width = 0;
1686 int status = state.surface->query(
1687 NATIVE_WINDOW_WIDTH, &width);
1688 ALOGE_IF(status != NO_ERROR,
1689 "Unable to query width (%d)", status);
1690 int height = 0;
1691 status = state.surface->query(
1692 NATIVE_WINDOW_HEIGHT, &height);
1693 ALOGE_IF(status != NO_ERROR,
1694 "Unable to query height (%d)", status);
1695 if (mUseHwcVirtualDisplays &&
1696 (MAX_VIRTUAL_DISPLAY_DIMENSION == 0 ||
1697 (width <= MAX_VIRTUAL_DISPLAY_DIMENSION &&
1698 height <= MAX_VIRTUAL_DISPLAY_DIMENSION))) {
1699 hwcDisplayId = allocateHwcDisplayId(state.type);
1700 }
1701
1702 sp<VirtualDisplaySurface> vds = new VirtualDisplaySurface(
1703 *mHwc, hwcDisplayId, state.surface,
1704 bqProducer, bqConsumer, state.displayName);
1705
1706 dispSurface = vds;
1707 producer = vds;
1708 }
1709 } else {
1710 ALOGE_IF(state.surface!=NULL,
1711 "adding a supported display, but rendering "
1712 "surface is provided (%p), ignoring it",
1713 state.surface.get());
1714 hwcDisplayId = allocateHwcDisplayId(state.type);
1715 // for supported (by hwc) displays we provide our
1716 // own rendering surface
1717 dispSurface = new FramebufferSurface(*mHwc, state.type,
1718 bqConsumer);
1719 producer = bqProducer;
1720 }
1721
1722 const wp<IBinder>& display(curr.keyAt(i));
1723 if (dispSurface != NULL) {
1724 sp<DisplayDevice> hw = new DisplayDevice(this,
1725 state.type, hwcDisplayId,
1726 mHwc->getFormat(hwcDisplayId), state.isSecure,
1727 display, dispSurface, producer,
1728 mRenderEngine->getEGLConfig());
1729 hw->setLayerStack(state.layerStack);
1730 hw->setProjection(state.orientation,
1731 state.viewport, state.frame);
1732 hw->setDisplayName(state.displayName);
1733 mDisplays.add(display, hw);
1734 if (state.isVirtualDisplay()) {
1735 if (hwcDisplayId >= 0) {
1736 mHwc->setVirtualDisplayProperties(hwcDisplayId,
1737 hw->getWidth(), hw->getHeight(),
1738 hw->getFormat());
1739 }
1740 } else {
1741 mEventThread->onHotplugReceived(state.type, true);
1742 }
1743 }
1744 }
1745 }
1746 }
1747 }
1748
1749 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1750 // The transform hint might have changed for some layers
1751 // (either because a display has changed, or because a layer
1752 // as changed).
1753 //
1754 // Walk through all the layers in currentLayers,
1755 // and update their transform hint.
1756 //
1757 // If a layer is visible only on a single display, then that
1758 // display is used to calculate the hint, otherwise we use the
1759 // default display.
1760 //
1761 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1762 // the hint is set before we acquire a buffer from the surface texture.
1763 //
1764 // NOTE: layer transactions have taken place already, so we use their
1765 // drawing state. However, SurfaceFlinger's own transaction has not
1766 // happened yet, so we must use the current state layer list
1767 // (soon to become the drawing state list).
1768 //
1769 sp<const DisplayDevice> disp;
1770 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08001771 bool first = true;
1772 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001773 // NOTE: we rely on the fact that layers are sorted by
1774 // layerStack first (so we don't have to traverse the list
1775 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07001776 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08001777 if (first || currentlayerStack != layerStack) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001778 currentlayerStack = layerStack;
1779 // figure out if this layerstack is mirrored
1780 // (more than one display) if so, pick the default display,
1781 // if not, pick the only display it's on.
1782 disp.clear();
1783 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1784 sp<const DisplayDevice> hw(mDisplays[dpy]);
1785 if (hw->getLayerStack() == currentlayerStack) {
1786 if (disp == NULL) {
1787 disp = hw;
1788 } else {
1789 disp = NULL;
1790 break;
1791 }
1792 }
1793 }
1794 }
1795 if (disp == NULL) {
1796 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1797 // redraw after transform hint changes. See bug 8508397.
1798
1799 // could be null when this layer is using a layerStack
1800 // that is not visible on any display. Also can occur at
1801 // screen off/on times.
1802 disp = getDefaultDisplayDevice();
1803 }
1804 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08001805
1806 first = false;
1807 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001808 }
1809
1810
1811 /*
1812 * Perform our own transaction if needed
1813 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07001814
1815 if (mLayersAdded) {
1816 mLayersAdded = false;
1817 // Layers have been added.
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001818 mVisibleRegionsDirty = true;
1819 }
1820
1821 // some layers might have been removed, so
1822 // we need to update the regions they're exposing.
1823 if (mLayersRemoved) {
1824 mLayersRemoved = false;
1825 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001826 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001827 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001828 // this layer is not visible anymore
1829 // TODO: we could traverse the tree from front to back and
1830 // compute the actual visible region
1831 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07001832 Region visibleReg;
1833 visibleReg.set(layer->computeScreenBounds());
1834 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001835 }
Robert Carr2047fae2016-11-28 14:09:09 -08001836 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001837 }
1838
1839 commitTransaction();
1840
1841 updateCursorAsync();
1842}
1843
1844void SurfaceFlinger::updateCursorAsync()
1845{
1846 HWComposer& hwc(getHwComposer());
1847 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1848 sp<const DisplayDevice> hw(mDisplays[dpy]);
1849 const int32_t id = hw->getHwcDisplayId();
1850 if (id < 0) {
1851 continue;
1852 }
1853 const Vector< sp<Layer> >& currentLayers(
1854 hw->getVisibleLayersSortedByZ());
1855 const size_t count = currentLayers.size();
1856 HWComposer::LayerListIterator cur = hwc.begin(id);
1857 const HWComposer::LayerListIterator end = hwc.end(id);
1858 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1859 if (cur->getCompositionType() != HWC_CURSOR_OVERLAY) {
1860 continue;
1861 }
1862 const sp<Layer>& layer(currentLayers[i]);
1863 Rect cursorPos = layer->getPosition(hw);
1864 hwc.setCursorPositionAsync(id, cursorPos);
1865 break;
1866 }
1867 }
1868}
1869
1870void SurfaceFlinger::commitTransaction()
1871{
1872 if (!mLayersPendingRemoval.isEmpty()) {
1873 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07001874 for (const auto& l : mLayersPendingRemoval) {
1875 recordBufferingStats(l->getName().string(),
1876 l->getOccupancyHistory(true));
1877 l->onRemoved();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001878 }
1879 mLayersPendingRemoval.clear();
1880 }
1881
1882 // If this transaction is part of a window animation then the next frame
1883 // we composite should be considered an animation as well.
1884 mAnimCompositionPending = mAnimTransactionPending;
1885
1886 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001887 mDrawingState.traverseInZOrder([](Layer* layer) {
1888 layer->commitChildList();
1889 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001890 mTransactionPending = false;
1891 mAnimTransactionPending = false;
1892 mTransactionCV.broadcast();
1893}
1894
Robert Carr2047fae2016-11-28 14:09:09 -08001895void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001896 Region& outDirtyRegion, Region& outOpaqueRegion)
1897{
1898 ATRACE_CALL();
1899
1900 Region aboveOpaqueLayers;
1901 Region aboveCoveredLayers;
1902 Region dirty;
1903
1904 outDirtyRegion.clear();
1905
Robert Carr2047fae2016-11-28 14:09:09 -08001906 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001907 // start with the whole surface at its current location
1908 const Layer::State& s(layer->getDrawingState());
1909
1910 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07001911 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08001912 return;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001913
1914 /*
1915 * opaqueRegion: area of a surface that is fully opaque.
1916 */
1917 Region opaqueRegion;
1918
1919 /*
1920 * visibleRegion: area of a surface that is visible on screen
1921 * and not fully transparent. This is essentially the layer's
1922 * footprint minus the opaque regions above it.
1923 * Areas covered by a translucent surface are considered visible.
1924 */
1925 Region visibleRegion;
1926
1927 /*
1928 * coveredRegion: area of a surface that is covered by all
1929 * visible regions above it (which includes the translucent areas).
1930 */
1931 Region coveredRegion;
1932
1933 /*
1934 * transparentRegion: area of a surface that is hinted to be completely
1935 * transparent. This is only used to tell when the layer has no visible
1936 * non-transparent regions and can be removed from the layer list. It
1937 * does not affect the visibleRegion of this layer or any layers
1938 * beneath it. The hint may not be correct if apps don't respect the
1939 * SurfaceView restrictions (which, sadly, some don't).
1940 */
1941 Region transparentRegion;
1942
1943
1944 // handle hidden surfaces by setting the visible region to empty
1945 if (CC_LIKELY(layer->isVisible())) {
1946 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001947 Rect bounds(layer->computeScreenBounds());
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001948 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001949 Transform tr = layer->getTransform();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001950 if (!visibleRegion.isEmpty()) {
1951 // Remove the transparent area from the visible region
1952 if (translucent) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001953 if (tr.preserveRects()) {
1954 // transform the transparent region
1955 transparentRegion = tr.transform(s.activeTransparentRegion);
1956 } else {
1957 // transformation too complex, can't do the
1958 // transparent region optimization.
1959 transparentRegion.clear();
1960 }
1961 }
1962
1963 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07001964 const int32_t layerOrientation = tr.getOrientation();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001965 if (s.alpha==255 && !translucent &&
1966 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1967 // the opaque region is the layer's footprint
1968 opaqueRegion = visibleRegion;
1969 }
1970 }
1971 }
1972
1973 // Clip the covered region to the visible region
1974 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1975
1976 // Update aboveCoveredLayers for next (lower) layer
1977 aboveCoveredLayers.orSelf(visibleRegion);
1978
1979 // subtract the opaque region covered by the layers above us
1980 visibleRegion.subtractSelf(aboveOpaqueLayers);
1981
1982 // compute this layer's dirty region
1983 if (layer->contentDirty) {
1984 // we need to invalidate the whole region
1985 dirty = visibleRegion;
1986 // as well, as the old visible region
1987 dirty.orSelf(layer->visibleRegion);
1988 layer->contentDirty = false;
1989 } else {
1990 /* compute the exposed region:
1991 * the exposed region consists of two components:
1992 * 1) what's VISIBLE now and was COVERED before
1993 * 2) what's EXPOSED now less what was EXPOSED before
1994 *
1995 * note that (1) is conservative, we start with the whole
1996 * visible region but only keep what used to be covered by
1997 * something -- which mean it may have been exposed.
1998 *
1999 * (2) handles areas that were not covered by anything but got
2000 * exposed because of a resize.
2001 */
2002 const Region newExposed = visibleRegion - coveredRegion;
2003 const Region oldVisibleRegion = layer->visibleRegion;
2004 const Region oldCoveredRegion = layer->coveredRegion;
2005 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2006 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
2007 }
2008 dirty.subtractSelf(aboveOpaqueLayers);
2009
2010 // accumulate to the screen dirty region
2011 outDirtyRegion.orSelf(dirty);
2012
2013 // Update aboveOpaqueLayers for next (lower) layer
2014 aboveOpaqueLayers.orSelf(opaqueRegion);
2015
2016 // Store the visible region in screen space
2017 layer->setVisibleRegion(visibleRegion);
2018 layer->setCoveredRegion(coveredRegion);
2019 layer->setVisibleNonTransparentRegion(
2020 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002021 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002022
2023 outOpaqueRegion = aboveOpaqueLayers;
2024}
2025
2026void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2027 const Region& dirty) {
2028 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2029 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2030 if (hw->getLayerStack() == layerStack) {
2031 hw->dirtyRegion.orSelf(dirty);
2032 }
2033 }
2034}
2035
2036bool SurfaceFlinger::handlePageFlip()
2037{
Brian Andersond6927fb2016-07-23 23:37:30 -07002038 nsecs_t latchTime = systemTime();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002039 Region dirtyRegion;
2040
2041 bool visibleRegions = false;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002042 bool frameQueued = false;
2043
2044 // Store the set of layers that need updates. This set must not change as
2045 // buffers are being latched, as this could result in a deadlock.
2046 // Example: Two producers share the same command stream and:
2047 // 1.) Layer 0 is latched
2048 // 2.) Layer 0 gets a new frame
2049 // 2.) Layer 1 gets a new frame
2050 // 3.) Layer 1 is latched.
2051 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2052 // second frame. But layer 0's second frame could be waiting on display.
2053 Vector<Layer*> layersWithQueuedFrames;
Robert Carr2047fae2016-11-28 14:09:09 -08002054 mDrawingState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002055 if (layer->hasQueuedFrame()) {
2056 frameQueued = true;
2057 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002058 layersWithQueuedFrames.push_back(layer);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002059 } else {
2060 layer->useEmptyDamage();
2061 }
2062 } else {
2063 layer->useEmptyDamage();
2064 }
Robert Carr2047fae2016-11-28 14:09:09 -08002065 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002066 for (size_t i = 0, count = layersWithQueuedFrames.size() ; i<count ; i++) {
2067 Layer* layer = layersWithQueuedFrames[i];
Brian Andersond6927fb2016-07-23 23:37:30 -07002068 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002069 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002070 invalidateLayerStack(layer->getLayerStack(), dirty);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002071 }
2072
2073 mVisibleRegionsDirty |= visibleRegions;
2074
2075 // If we will need to wake up at some time in the future to deal with a
2076 // queued frame that shouldn't be displayed during this vsync period, wake
2077 // up during the next vsync period to check again.
2078 if (frameQueued && layersWithQueuedFrames.empty()) {
2079 signalLayerUpdate();
2080 }
2081
2082 // Only continue with the refresh if there is actually new work to do
2083 return !layersWithQueuedFrames.empty();
2084}
2085
2086void SurfaceFlinger::invalidateHwcGeometry()
2087{
2088 mHwWorkListDirty = true;
2089}
2090
2091
2092void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
2093 const Region& inDirtyRegion)
2094{
2095 // We only need to actually compose the display if:
2096 // 1) It is being handled by hardware composer, which may need this to
2097 // keep its virtual display state machine in sync, or
2098 // 2) There is work to be done (the dirty region isn't empty)
2099 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
2100 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
2101 return;
2102 }
2103
2104 Region dirtyRegion(inDirtyRegion);
2105
2106 // compute the invalid region
2107 hw->swapRegion.orSelf(dirtyRegion);
2108
2109 uint32_t flags = hw->getFlags();
2110 if (flags & DisplayDevice::SWAP_RECTANGLE) {
2111 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2112 // takes a rectangle, we must make sure to update that whole
2113 // rectangle in that case
2114 dirtyRegion.set(hw->swapRegion.bounds());
2115 } else {
2116 if (flags & DisplayDevice::PARTIAL_UPDATES) {
2117 // We need to redraw the rectangle that will be updated
2118 // (pushed to the framebuffer).
2119 // This is needed because PARTIAL_UPDATES only takes one
2120 // rectangle instead of a region (see DisplayDevice::flip())
2121 dirtyRegion.set(hw->swapRegion.bounds());
2122 } else {
2123 // we need to redraw everything (the whole screen)
2124 dirtyRegion.set(hw->bounds());
2125 hw->swapRegion = dirtyRegion;
2126 }
2127 }
2128
2129 if (CC_LIKELY(!mDaltonize && !mHasColorMatrix)) {
2130 if (!doComposeSurfaces(hw, dirtyRegion)) return;
2131 } else {
2132 RenderEngine& engine(getRenderEngine());
2133 mat4 colorMatrix = mColorMatrix;
2134 if (mDaltonize) {
2135 colorMatrix = colorMatrix * mDaltonizer();
2136 }
2137 mat4 oldMatrix = engine.setupColorTransform(colorMatrix);
2138 doComposeSurfaces(hw, dirtyRegion);
2139 engine.setupColorTransform(oldMatrix);
2140 }
2141
2142 // update the swap region and clear the dirty region
2143 hw->swapRegion.orSelf(dirtyRegion);
2144
2145 // swap buffers (presentation)
2146 hw->swapBuffers(getHwComposer());
2147}
2148
2149bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
2150{
2151 RenderEngine& engine(getRenderEngine());
2152 const int32_t id = hw->getHwcDisplayId();
2153 HWComposer& hwc(getHwComposer());
2154 HWComposer::LayerListIterator cur = hwc.begin(id);
2155 const HWComposer::LayerListIterator end = hwc.end(id);
2156
2157 bool hasGlesComposition = hwc.hasGlesComposition(id);
2158 if (hasGlesComposition) {
2159 if (!hw->makeCurrent(mEGLDisplay, mEGLContext)) {
2160 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
2161 hw->getDisplayName().string());
2162 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2163 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2164 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2165 }
2166 return false;
2167 }
2168
2169 // Never touch the framebuffer if we don't have any framebuffer layers
2170 const bool hasHwcComposition = hwc.hasHwcComposition(id);
2171 if (hasHwcComposition) {
2172 // when using overlays, we assume a fully transparent framebuffer
2173 // NOTE: we could reduce how much we need to clear, for instance
2174 // remove where there are opaque FB layers. however, on some
2175 // GPUs doing a "clean slate" clear might be more efficient.
2176 // We'll revisit later if needed.
2177 engine.clearWithColor(0, 0, 0, 0);
2178 } else {
2179 // we start with the whole screen area
2180 const Region bounds(hw->getBounds());
2181
2182 // we remove the scissor part
2183 // we're left with the letterbox region
2184 // (common case is that letterbox ends-up being empty)
2185 const Region letterbox(bounds.subtract(hw->getScissor()));
2186
2187 // compute the area to clear
2188 Region region(hw->undefinedRegion.merge(letterbox));
2189
2190 // but limit it to the dirty region
2191 region.andSelf(dirty);
2192
2193 // screen is already cleared here
2194 if (!region.isEmpty()) {
2195 // can happen with SurfaceView
2196 drawWormhole(hw, region);
2197 }
2198 }
2199
2200 if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
2201 // just to be on the safe side, we don't set the
2202 // scissor on the main display. It should never be needed
2203 // anyways (though in theory it could since the API allows it).
2204 const Rect& bounds(hw->getBounds());
2205 const Rect& scissor(hw->getScissor());
2206 if (scissor != bounds) {
2207 // scissor doesn't match the screen's dimensions, so we
2208 // need to clear everything outside of it and enable
2209 // the GL scissor so we don't draw anything where we shouldn't
2210
2211 // enable scissor for this frame
2212 const uint32_t height = hw->getHeight();
2213 engine.setScissor(scissor.left, height - scissor.bottom,
2214 scissor.getWidth(), scissor.getHeight());
2215 }
2216 }
2217 }
2218
2219 /*
2220 * and then, render the layers targeted at the framebuffer
2221 */
2222
2223 const Vector< sp<Layer> >& layers(hw->getVisibleLayersSortedByZ());
2224 const size_t count = layers.size();
2225 const Transform& tr = hw->getTransform();
2226 if (cur != end) {
2227 // we're using h/w composer
2228 for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
2229 const sp<Layer>& layer(layers[i]);
2230 const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
2231 if (!clip.isEmpty()) {
2232 switch (cur->getCompositionType()) {
2233 case HWC_CURSOR_OVERLAY:
2234 case HWC_OVERLAY: {
2235 const Layer::State& state(layer->getDrawingState());
2236 if ((cur->getHints() & HWC_HINT_CLEAR_FB)
2237 && i
2238 && layer->isOpaque(state) && (state.alpha == 0xFF)
2239 && hasGlesComposition) {
2240 // never clear the very first layer since we're
2241 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002242 layer->clearWithOpenGL(hw);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002243 }
2244 break;
2245 }
2246 case HWC_FRAMEBUFFER: {
2247 layer->draw(hw, clip);
2248 break;
2249 }
2250 case HWC_FRAMEBUFFER_TARGET: {
2251 // this should not happen as the iterator shouldn't
2252 // let us get there.
2253 ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%zu)", i);
2254 break;
2255 }
2256 }
2257 }
2258 layer->setAcquireFence(hw, *cur);
2259 }
2260 } else {
2261 // we're not using h/w composer
2262 for (size_t i=0 ; i<count ; ++i) {
2263 const sp<Layer>& layer(layers[i]);
2264 const Region clip(dirty.intersect(
2265 tr.transform(layer->visibleRegion)));
2266 if (!clip.isEmpty()) {
2267 layer->draw(hw, clip);
2268 }
2269 }
2270 }
2271
2272 // disable scissor at the end of the frame
2273 engine.disableScissor();
2274 return true;
2275}
2276
2277void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
2278 const int32_t height = hw->getHeight();
2279 RenderEngine& engine(getRenderEngine());
2280 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
2281}
2282
2283status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
2284 const sp<IBinder>& handle,
2285 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002286 const sp<Layer>& lbc,
2287 const sp<Layer>& parent)
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002288{
2289 // add this layer to the current state list
2290 {
2291 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002292 if (mNumLayers >= MAX_LAYERS) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002293 return NO_MEMORY;
2294 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002295 if (parent == nullptr) {
2296 mCurrentState.layersSortedByZ.add(lbc);
2297 } else {
2298 parent->addChild(lbc);
2299 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002300 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002301 mLayersAdded = true;
2302 mNumLayers++;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002303 }
2304
2305 // attach this layer to the client
2306 client->attachLayer(handle, lbc);
2307
2308 return NO_ERROR;
2309}
2310
2311status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) {
2312 Mutex::Autolock _l(mStateLock);
2313 sp<Layer> layer = weakLayer.promote();
2314 if (layer == nullptr) {
2315 // The layer has already been removed, carry on
2316 return NO_ERROR;
2317 }
2318
Robert Carr1f0a16a2016-10-24 16:27:39 -07002319 const auto& p = layer->getParent();
2320 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2321 mCurrentState.layersSortedByZ.remove(layer);
2322
2323 if (index < 0) {
2324 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2325 layer->getName().string(),
2326 (p != nullptr) ? p->getName().string() : "no-parent");
2327 return BAD_VALUE;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002328 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002329
2330 mLayersPendingRemoval.add(layer);
2331 mLayersRemoved = true;
2332 mNumLayers--;
2333 setTransactionFlags(eTransactionNeeded);
2334 return NO_ERROR;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002335}
2336
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002337uint32_t SurfaceFlinger::peekTransactionFlags() {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002338 return android_atomic_release_load(&mTransactionFlags);
2339}
2340
2341uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
2342 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2343}
2344
2345uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
2346 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2347 if ((old & flags)==0) { // wake the server up
2348 signalTransaction();
2349 }
2350 return old;
2351}
2352
2353void SurfaceFlinger::setTransactionState(
2354 const Vector<ComposerState>& state,
2355 const Vector<DisplayState>& displays,
2356 uint32_t flags)
2357{
2358 ATRACE_CALL();
2359 Mutex::Autolock _l(mStateLock);
2360 uint32_t transactionFlags = 0;
2361
2362 if (flags & eAnimation) {
2363 // For window updates that are part of an animation we must wait for
2364 // previous animation "frames" to be handled.
2365 while (mAnimTransactionPending) {
2366 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2367 if (CC_UNLIKELY(err != NO_ERROR)) {
2368 // just in case something goes wrong in SF, return to the
2369 // caller after a few seconds.
2370 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2371 "waiting for previous animation frame");
2372 mAnimTransactionPending = false;
2373 break;
2374 }
2375 }
2376 }
2377
2378 size_t count = displays.size();
2379 for (size_t i=0 ; i<count ; i++) {
2380 const DisplayState& s(displays[i]);
2381 transactionFlags |= setDisplayStateLocked(s);
2382 }
2383
2384 count = state.size();
2385 for (size_t i=0 ; i<count ; i++) {
2386 const ComposerState& s(state[i]);
2387 // Here we need to check that the interface we're given is indeed
2388 // one of our own. A malicious client could give us a NULL
2389 // IInterface, or one of its own or even one of our own but a
2390 // different type. All these situations would cause us to crash.
2391 //
2392 // NOTE: it would be better to use RTTI as we could directly check
2393 // that we have a Client*. however, RTTI is disabled in Android.
2394 if (s.client != NULL) {
2395 sp<IBinder> binder = IInterface::asBinder(s.client);
2396 if (binder != NULL) {
Fabien Sanglard45b20252017-01-18 16:43:18 -08002397 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002398 sp<Client> client( static_cast<Client *>(s.client.get()) );
2399 transactionFlags |= setClientStateLocked(client, s.state);
2400 }
2401 }
2402 }
2403 }
2404
2405 // If a synchronous transaction is explicitly requested without any changes,
2406 // force a transaction anyway. This can be used as a flush mechanism for
2407 // previous async transactions.
2408 if (transactionFlags == 0 && (flags & eSynchronous)) {
2409 transactionFlags = eTransactionNeeded;
2410 }
2411
2412 if (transactionFlags) {
2413 if (mInterceptor.isEnabled()) {
2414 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2415 }
2416
2417 // this triggers the transaction
2418 setTransactionFlags(transactionFlags);
2419
2420 // if this is a synchronous transaction, wait for it to take effect
2421 // before returning.
2422 if (flags & eSynchronous) {
2423 mTransactionPending = true;
2424 }
2425 if (flags & eAnimation) {
2426 mAnimTransactionPending = true;
2427 }
2428 while (mTransactionPending) {
2429 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2430 if (CC_UNLIKELY(err != NO_ERROR)) {
2431 // just in case something goes wrong in SF, return to the
2432 // called after a few seconds.
2433 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2434 mTransactionPending = false;
2435 break;
2436 }
2437 }
2438 }
2439}
2440
2441uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2442{
2443 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2444 if (dpyIdx < 0)
2445 return 0;
2446
2447 uint32_t flags = 0;
2448 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
2449 if (disp.isValid()) {
2450 const uint32_t what = s.what;
2451 if (what & DisplayState::eSurfaceChanged) {
2452 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
2453 disp.surface = s.surface;
2454 flags |= eDisplayTransactionNeeded;
2455 }
2456 }
2457 if (what & DisplayState::eLayerStackChanged) {
2458 if (disp.layerStack != s.layerStack) {
2459 disp.layerStack = s.layerStack;
2460 flags |= eDisplayTransactionNeeded;
2461 }
2462 }
2463 if (what & DisplayState::eDisplayProjectionChanged) {
2464 if (disp.orientation != s.orientation) {
2465 disp.orientation = s.orientation;
2466 flags |= eDisplayTransactionNeeded;
2467 }
2468 if (disp.frame != s.frame) {
2469 disp.frame = s.frame;
2470 flags |= eDisplayTransactionNeeded;
2471 }
2472 if (disp.viewport != s.viewport) {
2473 disp.viewport = s.viewport;
2474 flags |= eDisplayTransactionNeeded;
2475 }
2476 }
2477 if (what & DisplayState::eDisplaySizeChanged) {
2478 if (disp.width != s.width) {
2479 disp.width = s.width;
2480 flags |= eDisplayTransactionNeeded;
2481 }
2482 if (disp.height != s.height) {
2483 disp.height = s.height;
2484 flags |= eDisplayTransactionNeeded;
2485 }
2486 }
2487 }
2488 return flags;
2489}
2490
2491uint32_t SurfaceFlinger::setClientStateLocked(
2492 const sp<Client>& client,
2493 const layer_state_t& s)
2494{
2495 uint32_t flags = 0;
2496 sp<Layer> layer(client->getLayerUser(s.surface));
2497 if (layer != 0) {
2498 const uint32_t what = s.what;
2499 bool geometryAppliesWithResize =
2500 what & layer_state_t::eGeometryAppliesWithResize;
2501 if (what & layer_state_t::ePositionChanged) {
2502 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
2503 flags |= eTraversalNeeded;
2504 }
2505 }
2506 if (what & layer_state_t::eLayerChanged) {
2507 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002508 const auto& p = layer->getParent();
2509 if (p == nullptr) {
2510 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2511 if (layer->setLayer(s.z) && idx >= 0) {
2512 mCurrentState.layersSortedByZ.removeAt(idx);
2513 mCurrentState.layersSortedByZ.add(layer);
2514 // we need traversal (state changed)
2515 // AND transaction (list changed)
2516 flags |= eTransactionNeeded|eTraversalNeeded;
2517 }
2518 } else {
2519 if (p->setChildLayer(layer, s.z)) {
2520 flags |= eTransactionNeeded|eTraversalNeeded;
2521 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002522 }
2523 }
2524 if (what & layer_state_t::eSizeChanged) {
2525 if (layer->setSize(s.w, s.h)) {
2526 flags |= eTraversalNeeded;
2527 }
2528 }
2529 if (what & layer_state_t::eAlphaChanged) {
2530 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
2531 flags |= eTraversalNeeded;
2532 }
2533 if (what & layer_state_t::eMatrixChanged) {
2534 if (layer->setMatrix(s.matrix))
2535 flags |= eTraversalNeeded;
2536 }
2537 if (what & layer_state_t::eTransparentRegionChanged) {
2538 if (layer->setTransparentRegionHint(s.transparentRegion))
2539 flags |= eTraversalNeeded;
2540 }
2541 if (what & layer_state_t::eFlagsChanged) {
2542 if (layer->setFlags(s.flags, s.mask))
2543 flags |= eTraversalNeeded;
2544 }
2545 if (what & layer_state_t::eCropChanged) {
2546 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
2547 flags |= eTraversalNeeded;
2548 }
2549 if (what & layer_state_t::eFinalCropChanged) {
2550 if (layer->setFinalCrop(s.finalCrop))
2551 flags |= eTraversalNeeded;
2552 }
2553 if (what & layer_state_t::eLayerStackChanged) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002554 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002555 // We only allow setting layer stacks for top level layers,
2556 // everything else inherits layer stack from its parent.
2557 if (layer->hasParent()) {
2558 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2559 layer->getName().string());
2560 } else if (idx < 0) {
2561 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2562 "that also does not appear in the top level layer list. Something"
2563 " has gone wrong.", layer->getName().string());
2564 } else if (layer->setLayerStack(s.layerStack)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002565 mCurrentState.layersSortedByZ.removeAt(idx);
2566 mCurrentState.layersSortedByZ.add(layer);
2567 // we need traversal (state changed)
2568 // AND transaction (list changed)
2569 flags |= eTransactionNeeded|eTraversalNeeded;
2570 }
2571 }
2572 if (what & layer_state_t::eDeferTransaction) {
2573 layer->deferTransactionUntil(s.handle, s.frameNumber);
2574 // We don't trigger a traversal here because if no other state is
2575 // changed, we don't want this to cause any more work
2576 }
Robert Carr1db73f62016-12-21 12:58:51 -08002577 if (what & layer_state_t::eReparentChildren) {
2578 if (layer->reparentChildren(s.reparentHandle)) {
2579 flags |= eTransactionNeeded|eTraversalNeeded;
2580 }
2581 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002582 if (what & layer_state_t::eOverrideScalingModeChanged) {
2583 layer->setOverrideScalingMode(s.overrideScalingMode);
2584 // We don't trigger a traversal here because if no other state is
2585 // changed, we don't want this to cause any more work
2586 }
2587 }
2588 return flags;
2589}
2590
2591status_t SurfaceFlinger::createLayer(
2592 const String8& name,
2593 const sp<Client>& client,
2594 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002595 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2596 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002597{
2598 if (int32_t(w|h) < 0) {
2599 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
2600 int(w), int(h));
2601 return BAD_VALUE;
2602 }
2603
2604 status_t result = NO_ERROR;
2605
2606 sp<Layer> layer;
2607
2608 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2609 case ISurfaceComposerClient::eFXSurfaceNormal:
2610 result = createNormalLayer(client,
2611 name, w, h, flags, format,
2612 handle, gbp, &layer);
2613 break;
2614 case ISurfaceComposerClient::eFXSurfaceDim:
2615 result = createDimLayer(client,
2616 name, w, h, flags,
2617 handle, gbp, &layer);
2618 break;
2619 default:
2620 result = BAD_VALUE;
2621 break;
2622 }
2623
2624 if (result != NO_ERROR) {
2625 return result;
2626 }
2627
Albert Chaulk479c60c2017-01-27 14:21:34 -05002628 layer->setInfo(windowType, ownerUid);
2629
Robert Carr1f0a16a2016-10-24 16:27:39 -07002630 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002631 if (result != NO_ERROR) {
2632 return result;
2633 }
2634 mInterceptor.saveSurfaceCreation(layer);
2635
2636 setTransactionFlags(eTransactionNeeded);
2637 return result;
2638}
2639
2640status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2641 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2642 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2643{
2644 // initialize the surfaces
2645 switch (format) {
2646 case PIXEL_FORMAT_TRANSPARENT:
2647 case PIXEL_FORMAT_TRANSLUCENT:
2648 format = PIXEL_FORMAT_RGBA_8888;
2649 break;
2650 case PIXEL_FORMAT_OPAQUE:
2651 format = PIXEL_FORMAT_RGBX_8888;
2652 break;
2653 }
2654
2655 *outLayer = new Layer(this, client, name, w, h, flags);
2656 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2657 if (err == NO_ERROR) {
2658 *handle = (*outLayer)->getHandle();
2659 *gbp = (*outLayer)->getProducer();
2660 }
2661
2662 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2663 return err;
2664}
2665
2666status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2667 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2668 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2669{
2670 *outLayer = new LayerDim(this, client, name, w, h, flags);
2671 *handle = (*outLayer)->getHandle();
2672 *gbp = (*outLayer)->getProducer();
2673 return NO_ERROR;
2674}
2675
2676status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
2677{
2678 // called by the window manager when it wants to remove a Layer
2679 status_t err = NO_ERROR;
2680 sp<Layer> l(client->getLayerUser(handle));
2681 if (l != NULL) {
2682 mInterceptor.saveSurfaceDeletion(l);
2683 err = removeLayer(l);
2684 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2685 "error removing layer=%p (%s)", l.get(), strerror(-err));
2686 }
2687 return err;
2688}
2689
2690status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
2691{
2692 // called by ~LayerCleaner() when all references to the IBinder (handle)
2693 // are gone
2694 return removeLayer(layer);
2695}
2696
2697// ---------------------------------------------------------------------------
2698
2699void SurfaceFlinger::onInitializeDisplays() {
2700 // reset screen orientation and use primary layer stack
2701 Vector<ComposerState> state;
2702 Vector<DisplayState> displays;
2703 DisplayState d;
2704 d.what = DisplayState::eDisplayProjectionChanged |
2705 DisplayState::eLayerStackChanged;
2706 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
2707 d.layerStack = 0;
2708 d.orientation = DisplayState::eOrientationDefault;
2709 d.frame.makeInvalid();
2710 d.viewport.makeInvalid();
2711 d.width = 0;
2712 d.height = 0;
2713 displays.add(d);
2714 setTransactionState(state, displays, 0);
2715 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
2716
2717 const nsecs_t period =
2718 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2719 mAnimFrameTracker.setDisplayRefreshPeriod(period);
2720}
2721
2722void SurfaceFlinger::initializeDisplays() {
2723 class MessageScreenInitialized : public MessageBase {
2724 SurfaceFlinger* flinger;
2725 public:
2726 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2727 virtual bool handler() {
2728 flinger->onInitializeDisplays();
2729 return true;
2730 }
2731 };
2732 sp<MessageBase> msg = new MessageScreenInitialized(this);
2733 postMessageAsync(msg); // we may be called from main thread, use async message
2734}
2735
2736void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2737 int mode) {
2738 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2739 this);
2740 int32_t type = hw->getDisplayType();
2741 int currentMode = hw->getPowerMode();
2742
2743 if (mode == currentMode) {
2744 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
2745 return;
2746 }
2747
2748 hw->setPowerMode(mode);
2749 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2750 ALOGW("Trying to set power mode for virtual display");
2751 return;
2752 }
2753
2754 if (mInterceptor.isEnabled()) {
2755 Mutex::Autolock _l(mStateLock);
2756 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
2757 if (idx < 0) {
2758 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
2759 return;
2760 }
2761 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
2762 }
2763
2764 if (currentMode == HWC_POWER_MODE_OFF) {
2765 // Turn on the display
2766 getHwComposer().setPowerMode(type, mode);
2767 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2768 // FIXME: eventthread only knows about the main display right now
2769 mEventThread->onScreenAcquired();
2770 resyncToHardwareVsync(true);
2771 }
2772
2773 mVisibleRegionsDirty = true;
2774 mHasPoweredOff = true;
2775 repaintEverything();
2776
2777 struct sched_param param = {0};
2778 param.sched_priority = 1;
2779 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
2780 ALOGW("Couldn't set SCHED_FIFO on display on");
2781 }
2782 } else if (mode == HWC_POWER_MODE_OFF) {
2783 // Turn off the display
2784 struct sched_param param = {0};
2785 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
2786 ALOGW("Couldn't set SCHED_OTHER on display off");
2787 }
2788
2789 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2790 disableHardwareVsync(true); // also cancels any in-progress resync
2791
2792 // FIXME: eventthread only knows about the main display right now
2793 mEventThread->onScreenReleased();
2794 }
2795
2796 getHwComposer().setPowerMode(type, mode);
2797 mVisibleRegionsDirty = true;
2798 // from this point on, SF will stop drawing on this display
2799 } else {
2800 getHwComposer().setPowerMode(type, mode);
2801 }
2802}
2803
2804void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2805 class MessageSetPowerMode: public MessageBase {
2806 SurfaceFlinger& mFlinger;
2807 sp<IBinder> mDisplay;
2808 int mMode;
2809 public:
2810 MessageSetPowerMode(SurfaceFlinger& flinger,
2811 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2812 mDisplay(disp) { mMode = mode; }
2813 virtual bool handler() {
2814 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2815 if (hw == NULL) {
2816 ALOGE("Attempt to set power mode = %d for null display %p",
2817 mMode, mDisplay.get());
2818 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2819 ALOGW("Attempt to set power mode = %d for virtual display",
2820 mMode);
2821 } else {
2822 mFlinger.setPowerModeInternal(hw, mMode);
2823 }
2824 return true;
2825 }
2826 };
2827 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
2828 postMessageSync(msg);
2829}
2830
2831// ---------------------------------------------------------------------------
2832
2833status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2834{
2835 String8 result;
2836
2837 IPCThreadState* ipc = IPCThreadState::self();
2838 const int pid = ipc->getCallingPid();
2839 const int uid = ipc->getCallingUid();
2840 if ((uid != AID_SHELL) &&
2841 !PermissionCache::checkPermission(sDump, pid, uid)) {
2842 result.appendFormat("Permission Denial: "
2843 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
2844 } else {
2845 // Try to get the main lock, but give up after one second
2846 // (this would indicate SF is stuck, but we want to be able to
2847 // print something in dumpsys).
2848 status_t err = mStateLock.timedLock(s2ns(1));
2849 bool locked = (err == NO_ERROR);
2850 if (!locked) {
2851 result.appendFormat(
2852 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2853 "dumping anyways (no locks held)\n", strerror(-err), err);
2854 }
2855
2856 bool dumpAll = true;
2857 size_t index = 0;
2858 size_t numArgs = args.size();
2859 if (numArgs) {
2860 if ((index < numArgs) &&
2861 (args[index] == String16("--list"))) {
2862 index++;
2863 listLayersLocked(args, index, result);
2864 dumpAll = false;
2865 }
2866
2867 if ((index < numArgs) &&
2868 (args[index] == String16("--latency"))) {
2869 index++;
2870 dumpStatsLocked(args, index, result);
2871 dumpAll = false;
2872 }
2873
2874 if ((index < numArgs) &&
2875 (args[index] == String16("--latency-clear"))) {
2876 index++;
2877 clearStatsLocked(args, index, result);
2878 dumpAll = false;
2879 }
2880
2881 if ((index < numArgs) &&
2882 (args[index] == String16("--dispsync"))) {
2883 index++;
2884 mPrimaryDispSync.dump(result);
2885 dumpAll = false;
2886 }
2887
2888 if ((index < numArgs) &&
2889 (args[index] == String16("--static-screen"))) {
2890 index++;
2891 dumpStaticScreenStats(result);
2892 dumpAll = false;
2893 }
2894
2895 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07002896 (args[index] == String16("--frame-events"))) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002897 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07002898 dumpFrameEventsLocked(result);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002899 dumpAll = false;
2900 }
2901 }
2902
2903 if (dumpAll) {
2904 dumpAllLocked(args, index, result);
2905 }
2906
2907 if (locked) {
2908 mStateLock.unlock();
2909 }
2910 }
2911 write(fd, result.string(), result.size());
2912 return NO_ERROR;
2913}
2914
2915void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2916 size_t& /* index */, String8& result) const
2917{
Robert Carr2047fae2016-11-28 14:09:09 -08002918 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002919 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08002920 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002921}
2922
2923void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2924 String8& result) const
2925{
2926 String8 name;
2927 if (index < args.size()) {
2928 name = String8(args[index]);
2929 index++;
2930 }
2931
2932 const nsecs_t period =
2933 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2934 result.appendFormat("%" PRId64 "\n", period);
2935
2936 if (name.isEmpty()) {
2937 mAnimFrameTracker.dumpStats(result);
2938 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08002939 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002940 if (name == layer->getName()) {
2941 layer->dumpFrameStats(result);
2942 }
Robert Carr2047fae2016-11-28 14:09:09 -08002943 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002944 }
2945}
2946
2947void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2948 String8& /* result */)
2949{
2950 String8 name;
2951 if (index < args.size()) {
2952 name = String8(args[index]);
2953 index++;
2954 }
2955
Robert Carr2047fae2016-11-28 14:09:09 -08002956 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002957 if (name.isEmpty() || (name == layer->getName())) {
2958 layer->clearFrameStats();
2959 }
Robert Carr2047fae2016-11-28 14:09:09 -08002960 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002961
2962 mAnimFrameTracker.clearStats();
2963}
2964
2965// This should only be called from the main thread. Otherwise it would need
2966// the lock and should use mCurrentState rather than mDrawingState.
2967void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08002968 mDrawingState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002969 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08002970 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002971
2972 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2973}
2974
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002975void SurfaceFlinger::appendSfConfigString(String8& result) const
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002976{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002977 result.append(" [sf");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002978#ifdef HAS_CONTEXT_PRIORITY
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002979 result.append(" HAS_CONTEXT_PRIORITY");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002980#endif
2981#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002982 result.append(" NEVER_DEFAULT_TO_ASYNC_MODE");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002983#endif
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002984 if (isLayerTripleBufferingDisabled())
2985 result.append(" DISABLE_TRIPLE_BUFFERING");
2986 result.append("]");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002987}
2988
2989void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2990{
2991 result.appendFormat("Static screen stats:\n");
2992 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2993 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2994 float percent = 100.0f *
2995 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2996 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2997 b + 1, bucketTimeSec, percent);
2998 }
2999 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3000 float percent = 100.0f *
3001 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3002 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3003 NUM_BUCKETS - 1, bucketTimeSec, percent);
3004}
3005
Brian Andersond6927fb2016-07-23 23:37:30 -07003006void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3007 result.appendFormat("Layer frame timestamps:\n");
3008
3009 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3010 const size_t count = currentLayers.size();
3011 for (size_t i=0 ; i<count ; i++) {
3012 currentLayers[i]->dumpFrameEvents(result);
3013 }
3014}
3015
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003016void SurfaceFlinger::recordBufferingStats(const char* layerName,
3017 std::vector<OccupancyTracker::Segment>&& history) {
3018 Mutex::Autolock lock(mBufferingStatsMutex);
3019 auto& stats = mBufferingStats[layerName];
3020 for (const auto& segment : history) {
3021 if (!segment.usedThirdBuffer) {
3022 stats.twoBufferTime += segment.totalTime;
3023 }
3024 if (segment.occupancyAverage < 1.0f) {
3025 stats.doubleBufferedTime += segment.totalTime;
3026 } else if (segment.occupancyAverage < 2.0f) {
3027 stats.tripleBufferedTime += segment.totalTime;
3028 }
3029 ++stats.numSegments;
3030 stats.totalTime += segment.totalTime;
3031 }
3032}
3033
3034void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3035 result.append("Buffering stats:\n");
3036 result.append(" [Layer name] <Active time> <Two buffer> "
3037 "<Double buffered> <Triple buffered>\n");
3038 Mutex::Autolock lock(mBufferingStatsMutex);
3039 typedef std::tuple<std::string, float, float, float> BufferTuple;
3040 std::map<float, BufferTuple, std::greater<float>> sorted;
3041 for (const auto& statsPair : mBufferingStats) {
3042 const char* name = statsPair.first.c_str();
3043 const BufferingStats& stats = statsPair.second;
3044 if (stats.numSegments == 0) {
3045 continue;
3046 }
3047 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3048 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3049 stats.totalTime;
3050 float doubleBufferRatio = static_cast<float>(
3051 stats.doubleBufferedTime) / stats.totalTime;
3052 float tripleBufferRatio = static_cast<float>(
3053 stats.tripleBufferedTime) / stats.totalTime;
3054 sorted.insert({activeTime, {name, twoBufferRatio,
3055 doubleBufferRatio, tripleBufferRatio}});
3056 }
3057 for (const auto& sortedPair : sorted) {
3058 float activeTime = sortedPair.first;
3059 const BufferTuple& values = sortedPair.second;
3060 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3061 std::get<0>(values).c_str(), activeTime,
3062 std::get<1>(values), std::get<2>(values),
3063 std::get<3>(values));
3064 }
3065 result.append("\n");
3066}
3067
3068void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3069 String8& result) const
3070{
3071 bool colorize = false;
3072 if (index < args.size()
3073 && (args[index] == String16("--color"))) {
3074 colorize = true;
3075 index++;
3076 }
3077
3078 Colorizer colorizer(colorize);
3079
3080 // figure out if we're stuck somewhere
3081 const nsecs_t now = systemTime();
3082 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3083 const nsecs_t inTransaction(mDebugInTransaction);
3084 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3085 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3086
3087 /*
3088 * Dump library configuration.
3089 */
3090
3091 colorizer.bold(result);
3092 result.append("Build configuration:");
3093 colorizer.reset(result);
3094 appendSfConfigString(result);
3095 appendUiConfigString(result);
3096 appendGuiConfigString(result);
3097 result.append("\n");
3098
3099 colorizer.bold(result);
3100 result.append("Sync configuration: ");
3101 colorizer.reset(result);
3102 result.append(SyncFeatures::getInstance().toString());
3103 result.append("\n");
3104
3105 colorizer.bold(result);
3106 result.append("DispSync configuration: ");
3107 colorizer.reset(result);
3108 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3109 "present offset %d ns (refresh %" PRId64 " ns)",
3110 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, PRESENT_TIME_OFFSET_FROM_VSYNC_NS,
3111 mHwc->getRefreshPeriod(HWC_DISPLAY_PRIMARY));
3112 result.append("\n");
3113
3114 // Dump static screen stats
3115 result.append("\n");
3116 dumpStaticScreenStats(result);
3117 result.append("\n");
3118
3119 dumpBufferingStats(result);
3120
3121 /*
3122 * Dump the visible layer list
3123 */
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003124 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003125 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003126 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003127 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003128 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003129 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003130
3131 /*
3132 * Dump Display state
3133 */
3134
3135 colorizer.bold(result);
3136 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
3137 colorizer.reset(result);
3138 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3139 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
3140 hw->dump(result);
3141 }
3142
3143 /*
3144 * Dump SurfaceFlinger global state
3145 */
3146
3147 colorizer.bold(result);
3148 result.append("SurfaceFlinger global state:\n");
3149 colorizer.reset(result);
3150
3151 HWComposer& hwc(getHwComposer());
3152 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3153
3154 colorizer.bold(result);
3155 result.appendFormat("EGL implementation : %s\n",
3156 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3157 colorizer.reset(result);
3158 result.appendFormat("%s\n",
3159 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
3160
3161 mRenderEngine->dump(result);
3162
3163 hw->undefinedRegion.dump(result, "undefinedRegion");
3164 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3165 hw->getOrientation(), hw->isDisplayOn());
3166 result.appendFormat(
3167 " last eglSwapBuffers() time: %f us\n"
3168 " last transaction time : %f us\n"
3169 " transaction-flags : %08x\n"
3170 " refresh-rate : %f fps\n"
3171 " x-dpi : %f\n"
3172 " y-dpi : %f\n"
3173 " gpu_to_cpu_unsupported : %d\n"
3174 ,
3175 mLastSwapBufferTime/1000.0,
3176 mLastTransactionTime/1000.0,
3177 mTransactionFlags,
3178 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
3179 hwc.getDpiX(HWC_DISPLAY_PRIMARY),
3180 hwc.getDpiY(HWC_DISPLAY_PRIMARY),
3181 !mGpuToCpuSupported);
3182
3183 result.appendFormat(" eglSwapBuffers time: %f us\n",
3184 inSwapBuffersDuration/1000.0);
3185
3186 result.appendFormat(" transaction time: %f us\n",
3187 inTransactionDuration/1000.0);
3188
3189 /*
3190 * VSYNC state
3191 */
3192 mEventThread->dump(result);
3193
3194 /*
3195 * Dump HWComposer state
3196 */
3197 colorizer.bold(result);
3198 result.append("h/w composer state:\n");
3199 colorizer.reset(result);
3200 result.appendFormat(" h/w composer %s and %s\n",
3201 hwc.initCheck()==NO_ERROR ? "present" : "not present",
3202 (mDebugDisableHWC || mDebugRegion || mDaltonize
3203 || mHasColorMatrix) ? "disabled" : "enabled");
3204 hwc.dump(result);
3205
3206 /*
3207 * Dump gralloc state
3208 */
3209 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3210 alloc.dump(result);
3211}
3212
3213const Vector< sp<Layer> >&
3214SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
3215 // Note: mStateLock is held here
3216 wp<IBinder> dpy;
3217 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3218 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3219 dpy = mDisplays.keyAt(i);
3220 break;
3221 }
3222 }
3223 if (dpy == NULL) {
3224 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3225 // Just use the primary display so we have something to return
3226 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3227 }
3228 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
3229}
3230
3231bool SurfaceFlinger::startDdmConnection()
3232{
3233 void* libddmconnection_dso =
3234 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3235 if (!libddmconnection_dso) {
3236 return false;
3237 }
3238 void (*DdmConnection_start)(const char* name);
3239 DdmConnection_start =
3240 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
3241 if (!DdmConnection_start) {
3242 dlclose(libddmconnection_dso);
3243 return false;
3244 }
3245 (*DdmConnection_start)(getServiceName());
3246 return true;
3247}
3248
3249status_t SurfaceFlinger::onTransact(
3250 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3251{
3252 switch (code) {
3253 case CREATE_CONNECTION:
3254 case CREATE_DISPLAY:
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003255 case BOOT_FINISHED:
3256 case CLEAR_ANIMATION_FRAME_STATS:
3257 case GET_ANIMATION_FRAME_STATS:
3258 case SET_POWER_MODE:
3259 case GET_HDR_CAPABILITIES:
3260 {
3261 // codes that require permission check
3262 IPCThreadState* ipc = IPCThreadState::self();
3263 const int pid = ipc->getCallingPid();
3264 const int uid = ipc->getCallingUid();
3265 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3266 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3267 ALOGE("Permission Denial: "
3268 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3269 return PERMISSION_DENIED;
3270 }
3271 break;
3272 }
Robert Carr1db73f62016-12-21 12:58:51 -08003273 /*
3274 * Calling setTransactionState is safe, because you need to have been
3275 * granted a reference to Client* and Handle* to do anything with it.
3276 *
3277 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3278 */
3279 case SET_TRANSACTION_STATE:
3280 case CREATE_SCOPED_CONNECTION:
3281 {
3282 break;
3283 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003284 case CAPTURE_SCREEN:
3285 {
3286 // codes that require permission check
3287 IPCThreadState* ipc = IPCThreadState::self();
3288 const int pid = ipc->getCallingPid();
3289 const int uid = ipc->getCallingUid();
3290 if ((uid != AID_GRAPHICS) &&
3291 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
3292 ALOGE("Permission Denial: "
3293 "can't read framebuffer pid=%d, uid=%d", pid, uid);
3294 return PERMISSION_DENIED;
3295 }
3296 break;
3297 }
3298 }
3299
3300 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3301 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
3302 CHECK_INTERFACE(ISurfaceComposer, data, reply);
3303 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
3304 IPCThreadState* ipc = IPCThreadState::self();
3305 const int pid = ipc->getCallingPid();
3306 const int uid = ipc->getCallingUid();
3307 ALOGE("Permission Denial: "
3308 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3309 return PERMISSION_DENIED;
3310 }
3311 int n;
3312 switch (code) {
3313 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
3314 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
3315 return NO_ERROR;
3316 case 1002: // SHOW_UPDATES
3317 n = data.readInt32();
3318 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
3319 invalidateHwcGeometry();
3320 repaintEverything();
3321 return NO_ERROR;
3322 case 1004:{ // repaint everything
3323 repaintEverything();
3324 return NO_ERROR;
3325 }
3326 case 1005:{ // force transaction
3327 setTransactionFlags(
3328 eTransactionNeeded|
3329 eDisplayTransactionNeeded|
3330 eTraversalNeeded);
3331 return NO_ERROR;
3332 }
3333 case 1006:{ // send empty update
3334 signalRefresh();
3335 return NO_ERROR;
3336 }
3337 case 1008: // toggle use of hw composer
3338 n = data.readInt32();
3339 mDebugDisableHWC = n ? 1 : 0;
3340 invalidateHwcGeometry();
3341 repaintEverything();
3342 return NO_ERROR;
3343 case 1009: // toggle use of transform hint
3344 n = data.readInt32();
3345 mDebugDisableTransformHint = n ? 1 : 0;
3346 invalidateHwcGeometry();
3347 repaintEverything();
3348 return NO_ERROR;
3349 case 1010: // interrogate.
3350 reply->writeInt32(0);
3351 reply->writeInt32(0);
3352 reply->writeInt32(mDebugRegion);
3353 reply->writeInt32(0);
3354 reply->writeInt32(mDebugDisableHWC);
3355 return NO_ERROR;
3356 case 1013: {
3357 Mutex::Autolock _l(mStateLock);
3358 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3359 reply->writeInt32(hw->getPageFlipCount());
3360 return NO_ERROR;
3361 }
3362 case 1014: {
3363 // daltonize
3364 n = data.readInt32();
3365 switch (n % 10) {
3366 case 1:
3367 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3368 break;
3369 case 2:
3370 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3371 break;
3372 case 3:
3373 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3374 break;
3375 }
3376 if (n >= 10) {
3377 mDaltonizer.setMode(ColorBlindnessMode::Correction);
3378 } else {
3379 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
3380 }
3381 mDaltonize = n > 0;
3382 invalidateHwcGeometry();
3383 repaintEverything();
3384 return NO_ERROR;
3385 }
3386 case 1015: {
3387 // apply a color matrix
3388 n = data.readInt32();
3389 mHasColorMatrix = n ? 1 : 0;
3390 if (n) {
3391 // color matrix is sent as mat3 matrix followed by vec3
3392 // offset, then packed into a mat4 where the last row is
3393 // the offset and extra values are 0
3394 for (size_t i = 0 ; i < 4; i++) {
3395 for (size_t j = 0; j < 4; j++) {
3396 mColorMatrix[i][j] = data.readFloat();
3397 }
3398 }
3399 } else {
3400 mColorMatrix = mat4();
3401 }
3402 invalidateHwcGeometry();
3403 repaintEverything();
3404 return NO_ERROR;
3405 }
3406 // This is an experimental interface
3407 // Needs to be shifted to proper binder interface when we productize
3408 case 1016: {
3409 n = data.readInt32();
3410 mPrimaryDispSync.setRefreshSkipCount(n);
3411 return NO_ERROR;
3412 }
3413 case 1017: {
3414 n = data.readInt32();
3415 mForceFullDamage = static_cast<bool>(n);
3416 return NO_ERROR;
3417 }
3418 case 1018: { // Modify Choreographer's phase offset
3419 n = data.readInt32();
3420 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3421 return NO_ERROR;
3422 }
3423 case 1019: { // Modify SurfaceFlinger's phase offset
3424 n = data.readInt32();
3425 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3426 return NO_ERROR;
3427 }
3428 case 1020: { // Layer updates interceptor
3429 n = data.readInt32();
3430 if (n) {
3431 ALOGV("Interceptor enabled");
3432 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
3433 }
3434 else{
3435 ALOGV("Interceptor disabled");
3436 mInterceptor.disable();
3437 }
3438 return NO_ERROR;
3439 }
3440 case 1021: { // Disable HWC virtual displays
3441 n = data.readInt32();
3442 mUseHwcVirtualDisplays = !n;
3443 return NO_ERROR;
3444 }
3445 }
3446 }
3447 return err;
3448}
3449
3450void SurfaceFlinger::repaintEverything() {
3451 android_atomic_or(1, &mRepaintEverything);
3452 signalTransaction();
3453}
3454
3455// ---------------------------------------------------------------------------
3456// Capture screen into an IGraphiBufferProducer
3457// ---------------------------------------------------------------------------
3458
3459/* The code below is here to handle b/8734824
3460 *
3461 * We create a IGraphicBufferProducer wrapper that forwards all calls
3462 * from the surfaceflinger thread to the calling binder thread, where they
3463 * are executed. This allows the calling thread in the calling process to be
3464 * reused and not depend on having "enough" binder threads to handle the
3465 * requests.
3466 */
3467class GraphicProducerWrapper : public BBinder, public MessageHandler {
3468 /* Parts of GraphicProducerWrapper are run on two different threads,
3469 * communicating by sending messages via Looper but also by shared member
3470 * data. Coherence maintenance is subtle and in places implicit (ugh).
3471 *
3472 * Don't rely on Looper's sendMessage/handleMessage providing
3473 * release/acquire semantics for any data not actually in the Message.
3474 * Data going from surfaceflinger to binder threads needs to be
3475 * synchronized explicitly.
3476 *
3477 * Barrier open/wait do provide release/acquire semantics. This provides
3478 * implicit synchronization for data coming back from binder to
3479 * surfaceflinger threads.
3480 */
3481
3482 sp<IGraphicBufferProducer> impl;
3483 sp<Looper> looper;
3484 status_t result;
3485 bool exitPending;
3486 bool exitRequested;
3487 Barrier barrier;
3488 uint32_t code;
3489 Parcel const* data;
3490 Parcel* reply;
3491
3492 enum {
3493 MSG_API_CALL,
3494 MSG_EXIT
3495 };
3496
3497 /*
3498 * Called on surfaceflinger thread. This is called by our "fake"
3499 * BpGraphicBufferProducer. We package the data and reply Parcel and
3500 * forward them to the binder thread.
3501 */
3502 virtual status_t transact(uint32_t code,
3503 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
3504 this->code = code;
3505 this->data = &data;
3506 this->reply = reply;
3507 if (exitPending) {
3508 // if we've exited, we run the message synchronously right here.
3509 // note (JH): as far as I can tell from looking at the code, this
3510 // never actually happens. if it does, i'm not sure if it happens
3511 // on the surfaceflinger or binder thread.
3512 handleMessage(Message(MSG_API_CALL));
3513 } else {
3514 barrier.close();
3515 // Prevent stores to this->{code, data, reply} from being
3516 // reordered later than the construction of Message.
3517 atomic_thread_fence(memory_order_release);
3518 looper->sendMessage(this, Message(MSG_API_CALL));
3519 barrier.wait();
3520 }
3521 return result;
3522 }
3523
3524 /*
3525 * here we run on the binder thread. All we've got to do is
3526 * call the real BpGraphicBufferProducer.
3527 */
3528 virtual void handleMessage(const Message& message) {
3529 int what = message.what;
3530 // Prevent reads below from happening before the read from Message
3531 atomic_thread_fence(memory_order_acquire);
3532 if (what == MSG_API_CALL) {
3533 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
3534 barrier.open();
3535 } else if (what == MSG_EXIT) {
3536 exitRequested = true;
3537 }
3538 }
3539
3540public:
3541 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3542 : impl(impl),
3543 looper(new Looper(true)),
3544 result(NO_ERROR),
3545 exitPending(false),
3546 exitRequested(false),
3547 code(0),
3548 data(NULL),
3549 reply(NULL)
3550 {}
3551
3552 // Binder thread
3553 status_t waitForResponse() {
3554 do {
3555 looper->pollOnce(-1);
3556 } while (!exitRequested);
3557 return result;
3558 }
3559
3560 // Client thread
3561 void exit(status_t result) {
3562 this->result = result;
3563 exitPending = true;
3564 // Ensure this->result is visible to the binder thread before it
3565 // handles the message.
3566 atomic_thread_fence(memory_order_release);
3567 looper->sendMessage(this, Message(MSG_EXIT));
3568 }
3569};
3570
3571
3572status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3573 const sp<IGraphicBufferProducer>& producer,
3574 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003575 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003576 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
3577
3578 if (CC_UNLIKELY(display == 0))
3579 return BAD_VALUE;
3580
3581 if (CC_UNLIKELY(producer == 0))
3582 return BAD_VALUE;
3583
3584 // if we have secure windows on this display, never allow the screen capture
3585 // unless the producer interface is local (i.e.: we can take a screenshot for
3586 // ourselves).
3587 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
3588
3589 // Convert to surfaceflinger's internal rotation type.
3590 Transform::orientation_flags rotationFlags;
3591 switch (rotation) {
3592 case ISurfaceComposer::eRotateNone:
3593 rotationFlags = Transform::ROT_0;
3594 break;
3595 case ISurfaceComposer::eRotate90:
3596 rotationFlags = Transform::ROT_90;
3597 break;
3598 case ISurfaceComposer::eRotate180:
3599 rotationFlags = Transform::ROT_180;
3600 break;
3601 case ISurfaceComposer::eRotate270:
3602 rotationFlags = Transform::ROT_270;
3603 break;
3604 default:
3605 rotationFlags = Transform::ROT_0;
3606 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3607 break;
3608 }
3609
3610 class MessageCaptureScreen : public MessageBase {
3611 SurfaceFlinger* flinger;
3612 sp<IBinder> display;
3613 sp<IGraphicBufferProducer> producer;
3614 Rect sourceCrop;
3615 uint32_t reqWidth, reqHeight;
Robert Carrae060832016-11-28 10:51:00 -08003616 int32_t minLayerZ,maxLayerZ;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003617 bool useIdentityTransform;
3618 Transform::orientation_flags rotation;
3619 status_t result;
3620 bool isLocalScreenshot;
3621 public:
3622 MessageCaptureScreen(SurfaceFlinger* flinger,
3623 const sp<IBinder>& display,
3624 const sp<IGraphicBufferProducer>& producer,
3625 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003626 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003627 bool useIdentityTransform,
3628 Transform::orientation_flags rotation,
3629 bool isLocalScreenshot)
3630 : flinger(flinger), display(display), producer(producer),
3631 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
3632 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
3633 useIdentityTransform(useIdentityTransform),
3634 rotation(rotation), result(PERMISSION_DENIED),
3635 isLocalScreenshot(isLocalScreenshot)
3636 {
3637 }
3638 status_t getResult() const {
3639 return result;
3640 }
3641 virtual bool handler() {
3642 Mutex::Autolock _l(flinger->mStateLock);
3643 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
3644 result = flinger->captureScreenImplLocked(hw, producer,
3645 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3646 useIdentityTransform, rotation, isLocalScreenshot);
3647 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
3648 return true;
3649 }
3650 };
3651
3652 // this creates a "fake" BBinder which will serve as a "fake" remote
3653 // binder to receive the marshaled calls and forward them to the
3654 // real remote (a BpGraphicBufferProducer)
3655 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3656
3657 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3658 // which does the marshaling work forwards to our "fake remote" above.
3659 sp<MessageBase> msg = new MessageCaptureScreen(this,
3660 display, IGraphicBufferProducer::asInterface( wrapper ),
3661 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3662 useIdentityTransform, rotationFlags, isLocalScreenshot);
3663
3664 status_t res = postMessageAsync(msg);
3665 if (res == NO_ERROR) {
3666 res = wrapper->waitForResponse();
3667 }
3668 return res;
3669}
3670
3671
3672void SurfaceFlinger::renderScreenImplLocked(
3673 const sp<const DisplayDevice>& hw,
3674 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003675 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003676 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
3677{
3678 ATRACE_CALL();
3679 RenderEngine& engine(getRenderEngine());
3680
3681 // get screen geometry
3682 const int32_t hw_w = hw->getWidth();
3683 const int32_t hw_h = hw->getHeight();
3684 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
3685 static_cast<int32_t>(reqHeight) != hw_h;
3686
3687 // if a default or invalid sourceCrop is passed in, set reasonable values
3688 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3689 !sourceCrop.isValid()) {
3690 sourceCrop.setLeftTop(Point(0, 0));
3691 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3692 }
3693
3694 // ensure that sourceCrop is inside screen
3695 if (sourceCrop.left < 0) {
3696 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3697 }
3698 if (sourceCrop.right > hw_w) {
3699 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
3700 }
3701 if (sourceCrop.top < 0) {
3702 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3703 }
3704 if (sourceCrop.bottom > hw_h) {
3705 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
3706 }
3707
3708 // make sure to clear all GL error flags
3709 engine.checkErrors();
3710
3711 // set-up our viewport
3712 engine.setViewportAndProjection(
3713 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
3714 engine.disableTexturing();
3715
3716 // redraw the screen entirely...
3717 engine.clearWithColor(0, 0, 0, 1);
3718
Robert Carr1f0a16a2016-10-24 16:27:39 -07003719 // We loop through the first level of layers without traversing,
3720 // as we need to interpret min/max layer Z in the top level Z space.
3721 for (const auto& layer : mDrawingState.layersSortedByZ) {
3722 if (layer->getLayerStack() != hw->getLayerStack()) {
3723 continue;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003724 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003725 const Layer::State& state(layer->getDrawingState());
3726 if (state.z < minLayerZ || state.z > maxLayerZ) {
3727 continue;
3728 }
3729 layer->traverseInZOrder([&](Layer* layer) {
3730 if (!layer->isVisible()) {
3731 return;
3732 }
3733 if (filtering) layer->setFiltering(true);
3734 layer->draw(hw, useIdentityTransform);
3735 if (filtering) layer->setFiltering(false);
3736 });
3737 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003738
3739 // compositionComplete is needed for older driver
3740 hw->compositionComplete();
3741 hw->setViewportAndProjection();
3742}
3743
3744
3745status_t SurfaceFlinger::captureScreenImplLocked(
3746 const sp<const DisplayDevice>& hw,
3747 const sp<IGraphicBufferProducer>& producer,
3748 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003749 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003750 bool useIdentityTransform, Transform::orientation_flags rotation,
3751 bool isLocalScreenshot)
3752{
3753 ATRACE_CALL();
3754
3755 // get screen geometry
3756 uint32_t hw_w = hw->getWidth();
3757 uint32_t hw_h = hw->getHeight();
3758
3759 if (rotation & Transform::ROT_90) {
3760 std::swap(hw_w, hw_h);
3761 }
3762
3763 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3764 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3765 reqWidth, reqHeight, hw_w, hw_h);
3766 return BAD_VALUE;
3767 }
3768
3769 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3770 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3771
3772 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07003773 for (const auto& layer : mDrawingState.layersSortedByZ) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003774 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07003775 if ((layer->getLayerStack() != hw->getLayerStack()) ||
3776 (state.z < minLayerZ || state.z > maxLayerZ)) {
3777 continue;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003778 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003779 layer->traverseInZOrder([&](Layer *layer) {
3780 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
3781 layer->isSecure());
3782 });
3783 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003784
3785 if (!isLocalScreenshot && secureLayerIsVisible) {
3786 ALOGW("FB is protected: PERMISSION_DENIED");
3787 return PERMISSION_DENIED;
3788 }
3789
3790 // create a surface (because we're a producer, and we need to
3791 // dequeue/queue a buffer)
3792 sp<Surface> sur = new Surface(producer, false);
3793 ANativeWindow* window = sur.get();
3794
3795 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3796 if (result == NO_ERROR) {
3797 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3798 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
3799
3800 int err = 0;
3801 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
3802 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
3803 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3804 err |= native_window_set_usage(window, usage);
3805
3806 if (err == NO_ERROR) {
3807 ANativeWindowBuffer* buffer;
3808 /* TODO: Once we have the sync framework everywhere this can use
3809 * server-side waits on the fence that dequeueBuffer returns.
3810 */
3811 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3812 if (result == NO_ERROR) {
3813 int syncFd = -1;
3814 // create an EGLImage from the buffer so we can later
3815 // turn it into a texture
3816 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3817 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3818 if (image != EGL_NO_IMAGE_KHR) {
3819 // this binds the given EGLImage as a framebuffer for the
3820 // duration of this scope.
3821 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3822 if (imageBond.getStatus() == NO_ERROR) {
3823 // this will in fact render into our dequeued buffer
3824 // via an FBO, which means we didn't have to create
3825 // an EGLSurface and therefore we're not
3826 // dependent on the context's EGLConfig.
3827 renderScreenImplLocked(
3828 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3829 useIdentityTransform, rotation);
3830
3831 // Attempt to create a sync khr object that can produce a sync point. If that
3832 // isn't available, create a non-dupable sync object in the fallback path and
3833 // wait on it directly.
3834 EGLSyncKHR sync;
3835 if (!DEBUG_SCREENSHOTS) {
3836 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
3837 // native fence fd will not be populated until flush() is done.
3838 getRenderEngine().flush();
3839 } else {
3840 sync = EGL_NO_SYNC_KHR;
3841 }
3842 if (sync != EGL_NO_SYNC_KHR) {
3843 // get the sync fd
3844 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3845 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3846 ALOGW("captureScreen: failed to dup sync khr object");
3847 syncFd = -1;
3848 }
3849 eglDestroySyncKHR(mEGLDisplay, sync);
3850 } else {
3851 // fallback path
3852 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3853 if (sync != EGL_NO_SYNC_KHR) {
3854 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3855 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3856 EGLint eglErr = eglGetError();
3857 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3858 ALOGW("captureScreen: fence wait timed out");
3859 } else {
3860 ALOGW_IF(eglErr != EGL_SUCCESS,
3861 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3862 }
3863 eglDestroySyncKHR(mEGLDisplay, sync);
3864 } else {
3865 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3866 }
3867 }
3868 if (DEBUG_SCREENSHOTS) {
3869 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3870 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3871 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3872 hw, minLayerZ, maxLayerZ);
3873 delete [] pixels;
3874 }
3875
3876 } else {
3877 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3878 result = INVALID_OPERATION;
3879 window->cancelBuffer(window, buffer, syncFd);
3880 buffer = NULL;
3881 }
3882 // destroy our image
3883 eglDestroyImageKHR(mEGLDisplay, image);
3884 } else {
3885 result = BAD_VALUE;
3886 }
3887 if (buffer) {
3888 // queueBuffer takes ownership of syncFd
3889 result = window->queueBuffer(window, buffer, syncFd);
3890 }
3891 }
3892 } else {
3893 result = BAD_VALUE;
3894 }
3895 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3896 }
3897
3898 return result;
3899}
3900
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003901void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08003902 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003903 if (DEBUG_SCREENSHOTS) {
3904 for (size_t y=0 ; y<h ; y++) {
3905 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3906 for (size_t x=0 ; x<w ; x++) {
3907 if (p[x] != 0xFF000000) return;
3908 }
3909 }
3910 ALOGE("*** we just took a black screenshot ***\n"
3911 "requested minz=%d, maxz=%d, layerStack=%d",
3912 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr2047fae2016-11-28 14:09:09 -08003913 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07003914 for (const auto& layer : mDrawingState.layersSortedByZ) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003915 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07003916 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
3917 state.z <= maxLayerZ) {
3918 layer->traverseInZOrder([&](Layer* layer) {
3919 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x",
3920 layer->isVisible() ? '+' : '-',
3921 i, layer->getName().string(), layer->getLayerStack(), state.z,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003922 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003923 i++;
3924 });
3925 }
3926 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003927 }
3928}
3929
3930// ---------------------------------------------------------------------------
3931
Robert Carr2047fae2016-11-28 14:09:09 -08003932void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
3933 layersSortedByZ.traverseInZOrder(consume);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003934}
3935
Robert Carr2047fae2016-11-28 14:09:09 -08003936void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
3937 layersSortedByZ.traverseInReverseZOrder(consume);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003938}
3939
3940}; // namespace android
3941
3942
3943#if defined(__gl_h_)
3944#error "don't include gl/gl.h in this file"
3945#endif
3946
3947#if defined(__gl2_h_)
3948#error "don't include gl2/gl2.h in this file"
3949#endif