blob: e6ab29a4fba07b5a1837382bd66be5dee1b8556c [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
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800191 property_get("debug.sf.enable_hwc_vds", value, "0");
192 mUseHwcVirtualDisplays = atoi(value);
193 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800194
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800195 property_get("ro.sf.disable_triple_buffer", value, "1");
196 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800197 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 Andersonb04c6f02016-10-21 12:57:46 -0700643 FrameEvent::GPU_COMPOSITION_DONE,
Brian Anderson3890c392016-07-25 12:48:08 -0700644 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
Steven Thomas3cfac282017-02-06 12:29:30 -08001021void SurfaceFlinger::onVSyncReceived(HWComposer* /*composer*/, int type,
1022 nsecs_t timestamp) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001023 bool needsHwVsync = false;
1024
1025 { // Scope for the lock
1026 Mutex::Autolock _l(mHWVsyncLock);
1027 if (type == 0 && mPrimaryHWVsyncEnabled) {
1028 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
1029 }
1030 }
1031
1032 if (needsHwVsync) {
1033 enableHardwareVsync();
1034 } else {
1035 disableHardwareVsync(false);
1036 }
1037}
1038
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001039void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
1040 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1041 *compositorTiming = mCompositorTiming;
1042}
1043
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001044void SurfaceFlinger::onHotplugReceived(int type, bool connected) {
1045 if (mEventThread == NULL) {
1046 // This is a temporary workaround for b/7145521. A non-null pointer
1047 // does not mean EventThread has finished initializing, so this
1048 // is not a correct fix.
1049 ALOGW("WARNING: EventThread not started, ignoring hotplug");
1050 return;
1051 }
1052
1053 if (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1054 Mutex::Autolock _l(mStateLock);
1055 if (connected) {
1056 createBuiltinDisplayLocked((DisplayDevice::DisplayType)type);
1057 } else {
1058 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1059 mBuiltinDisplays[type].clear();
1060 }
1061 setTransactionFlags(eDisplayTransactionNeeded);
1062
1063 // Defer EventThread notification until SF has updated mDisplays.
1064 }
1065}
1066
Steven Thomas3cfac282017-02-06 12:29:30 -08001067void SurfaceFlinger::onInvalidateReceived(HWComposer* /*composer*/) {
1068 repaintEverything();
1069}
1070
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001071void SurfaceFlinger::eventControl(int disp, int event, int enabled) {
1072 ATRACE_CALL();
1073 getHwComposer().eventControl(disp, event, enabled);
1074}
1075
1076void SurfaceFlinger::onMessageReceived(int32_t what) {
1077 ATRACE_CALL();
1078 switch (what) {
1079 case MessageQueue::INVALIDATE: {
1080 bool refreshNeeded = handleMessageTransaction();
1081 refreshNeeded |= handleMessageInvalidate();
1082 refreshNeeded |= mRepaintEverything;
1083 if (refreshNeeded) {
1084 // Signal a refresh if a transaction modified the window state,
1085 // a new buffer was latched, or if HWC has requested a full
1086 // repaint
1087 signalRefresh();
1088 }
1089 break;
1090 }
1091 case MessageQueue::REFRESH: {
1092 handleMessageRefresh();
1093 break;
1094 }
1095 }
1096}
1097
1098bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001099 uint32_t transactionFlags = peekTransactionFlags();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001100 if (transactionFlags) {
1101 handleTransaction(transactionFlags);
1102 return true;
1103 }
1104 return false;
1105}
1106
1107bool SurfaceFlinger::handleMessageInvalidate() {
1108 ATRACE_CALL();
1109 return handlePageFlip();
1110}
1111
1112void SurfaceFlinger::handleMessageRefresh() {
1113 ATRACE_CALL();
1114
1115 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1116
Brian Andersond6927fb2016-07-23 23:37:30 -07001117 preComposition(refreshStartTime);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001118 rebuildLayerStacks();
1119 setUpHWComposer();
1120 doDebugFlashRegions();
1121 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001122 postComposition(refreshStartTime);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001123}
1124
1125void SurfaceFlinger::doDebugFlashRegions()
1126{
1127 // is debugging enabled
1128 if (CC_LIKELY(!mDebugRegion))
1129 return;
1130
1131 const bool repaintEverything = mRepaintEverything;
1132 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1133 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1134 if (hw->isDisplayOn()) {
1135 // transform the dirty region into this screen's coordinate space
1136 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1137 if (!dirtyRegion.isEmpty()) {
1138 // redraw the whole screen
1139 doComposeSurfaces(hw, Region(hw->bounds()));
1140
1141 // and draw the dirty region
1142 const int32_t height = hw->getHeight();
1143 RenderEngine& engine(getRenderEngine());
1144 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1145
1146 hw->compositionComplete();
1147 hw->swapBuffers(getHwComposer());
1148 }
1149 }
1150 }
1151
1152 postFramebuffer();
1153
1154 if (mDebugRegion > 1) {
1155 usleep(mDebugRegion * 1000);
1156 }
1157
1158 HWComposer& hwc(getHwComposer());
1159 if (hwc.initCheck() == NO_ERROR) {
1160 status_t err = hwc.prepare();
1161 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1162 }
1163}
1164
Brian Andersond6927fb2016-07-23 23:37:30 -07001165void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001166{
1167 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001168 mDrawingState.traverseInZOrder([&](Layer* layer) {
1169 if (layer->onPreComposition(refreshStartTime)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001170 needExtraInvalidate = true;
1171 }
Robert Carr2047fae2016-11-28 14:09:09 -08001172 });
1173
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001174 if (needExtraInvalidate) {
1175 signalLayerUpdate();
1176 }
1177}
1178
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001179void SurfaceFlinger::updateCompositorTiming(
1180 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1181 std::shared_ptr<FenceTime>& presentFenceTime) {
1182 // Update queue of past composite+present times and determine the
1183 // most recently known composite to present latency.
1184 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1185 nsecs_t compositeToPresentLatency = -1;
1186 while (!mCompositePresentTimes.empty()) {
1187 CompositePresentTime& cpt = mCompositePresentTimes.front();
1188 // Cached values should have been updated before calling this method,
1189 // which helps avoid duplicate syscalls.
1190 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1191 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1192 break;
1193 }
1194 compositeToPresentLatency = displayTime - cpt.composite;
1195 mCompositePresentTimes.pop();
1196 }
1197
1198 // Don't let mCompositePresentTimes grow unbounded, just in case.
1199 while (mCompositePresentTimes.size() > 16) {
1200 mCompositePresentTimes.pop();
1201 }
1202
1203 // Integer division and modulo round toward 0 not -inf, so we need to
1204 // treat negative and positive offsets differently.
1205 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs >= 0) ?
1206 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1207 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1208
1209 // Snap the latency to a value that removes scheduling jitter from the
1210 // composition and present times, which often have >1ms of jitter.
1211 // Reducing jitter is important if an app attempts to extrapolate
1212 // something (such as user input) to an accurate diasplay time.
1213 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1214 // with (presentLatency % interval).
1215 nsecs_t snappedCompositeToPresentLatency = -1;
1216 if (compositeToPresentLatency >= 0) {
1217 nsecs_t bias = vsyncInterval / 2;
1218 int64_t extraVsyncs =
1219 (compositeToPresentLatency - idealLatency + bias) /
1220 vsyncInterval;
1221 nsecs_t extraLatency = extraVsyncs * vsyncInterval;
1222 snappedCompositeToPresentLatency = idealLatency + extraLatency;
1223 }
1224
1225 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1226 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1227 mCompositorTiming.interval = vsyncInterval;
1228 if (snappedCompositeToPresentLatency >= 0) {
1229 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
1230 }
1231}
1232
1233void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001234{
Brian Andersond6927fb2016-07-23 23:37:30 -07001235 const HWComposer& hwc = getHwComposer();
1236 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
1237
Brian Anderson3d4039d2016-09-23 16:31:30 -07001238 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1239 if (getHwComposer().hasGlesComposition(hw->getHwcDisplayId())) {
1240 glCompositionDoneFenceTime =
1241 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1242 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1243 } else {
1244 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1245 }
1246 mGlCompositionDoneTimeline.updateSignalTimes();
1247
1248 sp<Fence> displayFence = mHwc->getDisplayFence(HWC_DISPLAY_PRIMARY);
1249 const std::shared_ptr<FenceTime>& presentFenceTime = FenceTime::NO_FENCE;
1250 auto retireFenceTime = std::make_shared<FenceTime>(displayFence);
1251 mDisplayTimeline.push(retireFenceTime);
1252 mDisplayTimeline.updateSignalTimes();
Brian Andersond6927fb2016-07-23 23:37:30 -07001253
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001254 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1255 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1256
1257 // We use the refreshStartTime which might be sampled a little later than
1258 // when we started doing work for this frame, but that should be okay
1259 // since updateCompositorTiming has snapping logic.
1260 updateCompositorTiming(
1261 vsyncPhase, vsyncInterval, refreshStartTime, retireFenceTime);
1262
Robert Carr2047fae2016-11-28 14:09:09 -08001263 mDrawingState.traverseInZOrder([&](Layer* layer) {
1264 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001265 presentFenceTime, retireFenceTime, mCompositorTiming);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001266 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001267 recordBufferingStats(layer->getName().string(),
1268 layer->getOccupancyHistory(false));
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001269 }
Robert Carr2047fae2016-11-28 14:09:09 -08001270 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001271
Brian Anderson3d4039d2016-09-23 16:31:30 -07001272 if (displayFence->isValid()) {
1273 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001274 enableHardwareVsync();
1275 } else {
1276 disableHardwareVsync(false);
1277 }
1278 }
1279
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001280 if (kIgnorePresentFences) {
1281 if (hw->isDisplayOn()) {
1282 enableHardwareVsync();
1283 }
1284 }
1285
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001286 if (mAnimCompositionPending) {
1287 mAnimCompositionPending = false;
1288
Brian Anderson3d4039d2016-09-23 16:31:30 -07001289 if (retireFenceTime->isValid()) {
1290 mAnimFrameTracker.setActualPresentFence(std::move(retireFenceTime));
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001291 } else {
1292 // The HWC doesn't support present fences, so use the refresh
1293 // timestamp instead.
1294 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
1295 mAnimFrameTracker.setActualPresentTime(presentTime);
1296 }
1297 mAnimFrameTracker.advanceFrame();
1298 }
1299
1300 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1301 return;
1302 }
1303
1304 nsecs_t currentTime = systemTime();
1305 if (mHasPoweredOff) {
1306 mHasPoweredOff = false;
1307 } else {
1308 nsecs_t period = mPrimaryDispSync.getPeriod();
1309 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1310 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1311 if (numPeriods < NUM_BUCKETS - 1) {
1312 mFrameBuckets[numPeriods] += elapsedTime;
1313 } else {
1314 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1315 }
1316 mTotalTime += elapsedTime;
1317 }
1318 mLastSwapTime = currentTime;
1319}
1320
1321void SurfaceFlinger::rebuildLayerStacks() {
1322 // rebuild the visible layer list per screen
1323 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1324 ATRACE_CALL();
1325 mVisibleRegionsDirty = false;
1326 invalidateHwcGeometry();
1327
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001328 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1329 Region opaqueRegion;
1330 Region dirtyRegion;
1331 Vector< sp<Layer> > layersSortedByZ;
1332 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1333 const Transform& tr(hw->getTransform());
1334 const Rect bounds(hw->getBounds());
1335 if (hw->isDisplayOn()) {
Robert Carr2047fae2016-11-28 14:09:09 -08001336 computeVisibleRegions(hw->getLayerStack(), dirtyRegion,
1337 opaqueRegion);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001338
Robert Carr2047fae2016-11-28 14:09:09 -08001339 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001340 if (layer->getLayerStack() == hw->getLayerStack()) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001341 Region drawRegion(tr.transform(
1342 layer->visibleNonTransparentRegion));
1343 drawRegion.andSelf(bounds);
1344 if (!drawRegion.isEmpty()) {
1345 layersSortedByZ.add(layer);
1346 }
1347 }
Robert Carr2047fae2016-11-28 14:09:09 -08001348 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001349 }
1350 hw->setVisibleLayersSortedByZ(layersSortedByZ);
1351 hw->undefinedRegion.set(bounds);
1352 hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1353 hw->dirtyRegion.orSelf(dirtyRegion);
1354 }
1355 }
1356}
1357
1358void SurfaceFlinger::setUpHWComposer() {
1359 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1360 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1361 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1362 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1363
1364 // If nothing has changed (!dirty), don't recompose.
1365 // If something changed, but we don't currently have any visible layers,
1366 // and didn't when we last did a composition, then skip it this time.
1367 // The second rule does two things:
1368 // - When all layers are removed from a display, we'll emit one black
1369 // frame, then nothing more until we get new layers.
1370 // - When a display is created with a private layer stack, we won't
1371 // emit any black frames until a layer is added to the layer stack.
1372 bool mustRecompose = dirty && !(empty && wasEmpty);
1373
1374 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1375 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1376 mustRecompose ? "doing" : "skipping",
1377 dirty ? "+" : "-",
1378 empty ? "+" : "-",
1379 wasEmpty ? "+" : "-");
1380
1381 mDisplays[dpy]->beginFrame(mustRecompose);
1382
1383 if (mustRecompose) {
1384 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1385 }
1386 }
1387
1388 HWComposer& hwc(getHwComposer());
1389 if (hwc.initCheck() == NO_ERROR) {
1390 // build the h/w work list
1391 if (CC_UNLIKELY(mHwWorkListDirty)) {
1392 mHwWorkListDirty = false;
1393 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1394 sp<const DisplayDevice> hw(mDisplays[dpy]);
1395 const int32_t id = hw->getHwcDisplayId();
1396 if (id >= 0) {
1397 const Vector< sp<Layer> >& currentLayers(
1398 hw->getVisibleLayersSortedByZ());
1399 const size_t count = currentLayers.size();
1400 if (hwc.createWorkList(id, count) == NO_ERROR) {
1401 HWComposer::LayerListIterator cur = hwc.begin(id);
1402 const HWComposer::LayerListIterator end = hwc.end(id);
1403 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1404 const sp<Layer>& layer(currentLayers[i]);
1405 layer->setGeometry(hw, *cur);
1406 if (mDebugDisableHWC || mDebugRegion || mDaltonize || mHasColorMatrix) {
1407 cur->setSkip(true);
1408 }
1409 }
1410 }
1411 }
1412 }
1413 }
1414
1415 // set the per-frame data
1416 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1417 sp<const DisplayDevice> hw(mDisplays[dpy]);
1418 const int32_t id = hw->getHwcDisplayId();
1419 if (id >= 0) {
1420 const Vector< sp<Layer> >& currentLayers(
1421 hw->getVisibleLayersSortedByZ());
1422 const size_t count = currentLayers.size();
1423 HWComposer::LayerListIterator cur = hwc.begin(id);
1424 const HWComposer::LayerListIterator end = hwc.end(id);
1425 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1426 /*
1427 * update the per-frame h/w composer data for each layer
1428 * and build the transparent region of the FB
1429 */
1430 const sp<Layer>& layer(currentLayers[i]);
1431 layer->setPerFrameData(hw, *cur);
1432 }
1433 }
1434 }
1435
1436 // If possible, attempt to use the cursor overlay on each display.
1437 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1438 sp<const DisplayDevice> hw(mDisplays[dpy]);
1439 const int32_t id = hw->getHwcDisplayId();
1440 if (id >= 0) {
1441 const Vector< sp<Layer> >& currentLayers(
1442 hw->getVisibleLayersSortedByZ());
1443 const size_t count = currentLayers.size();
1444 HWComposer::LayerListIterator cur = hwc.begin(id);
1445 const HWComposer::LayerListIterator end = hwc.end(id);
1446 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1447 const sp<Layer>& layer(currentLayers[i]);
1448 if (layer->isPotentialCursor()) {
1449 cur->setIsCursorLayerHint();
1450 break;
1451 }
1452 }
1453 }
1454 }
1455
1456 status_t err = hwc.prepare();
1457 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1458
1459 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1460 sp<const DisplayDevice> hw(mDisplays[dpy]);
1461 hw->prepareFrame(hwc);
1462 }
1463 }
1464}
1465
1466void SurfaceFlinger::doComposition() {
1467 ATRACE_CALL();
1468 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
1469 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1470 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1471 if (hw->isDisplayOn()) {
1472 // transform the dirty region into this screen's coordinate space
1473 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1474
1475 // repaint the framebuffer (if needed)
1476 doDisplayComposition(hw, dirtyRegion);
1477
1478 hw->dirtyRegion.clear();
1479 hw->flip(hw->swapRegion);
1480 hw->swapRegion.clear();
1481 }
1482 // inform the h/w that we're done compositing
1483 hw->compositionComplete();
1484 }
1485 postFramebuffer();
1486}
1487
1488void SurfaceFlinger::postFramebuffer()
1489{
1490 ATRACE_CALL();
1491
1492 const nsecs_t now = systemTime();
1493 mDebugInSwapBuffers = now;
1494
1495 HWComposer& hwc(getHwComposer());
1496 if (hwc.initCheck() == NO_ERROR) {
1497 if (!hwc.supportsFramebufferTarget()) {
1498 // EGL spec says:
1499 // "surface must be bound to the calling thread's current context,
1500 // for the current rendering API."
1501 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1502 }
1503 hwc.commit();
1504 }
1505
1506 // make the default display current because the VirtualDisplayDevice code cannot
1507 // deal with dequeueBuffer() being called outside of the composition loop; however
1508 // the code below can call glFlush() which is allowed (and does in some case) call
1509 // dequeueBuffer().
1510 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1511
1512 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1513 sp<const DisplayDevice> hw(mDisplays[dpy]);
1514 const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ());
1515 hw->onSwapBuffersCompleted(hwc);
1516 const size_t count = currentLayers.size();
1517 int32_t id = hw->getHwcDisplayId();
1518 if (id >=0 && hwc.initCheck() == NO_ERROR) {
1519 HWComposer::LayerListIterator cur = hwc.begin(id);
1520 const HWComposer::LayerListIterator end = hwc.end(id);
1521 for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
1522 currentLayers[i]->onLayerDisplayed(hw, &*cur);
1523 }
1524 } else {
1525 for (size_t i = 0; i < count; i++) {
1526 currentLayers[i]->onLayerDisplayed(hw, NULL);
1527 }
1528 }
1529 }
1530
1531 mLastSwapBufferTime = systemTime() - now;
1532 mDebugInSwapBuffers = 0;
1533
1534 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1535 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1536 logFrameStats();
1537 }
1538}
1539
1540void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
1541{
1542 ATRACE_CALL();
1543
1544 // here we keep a copy of the drawing state (that is the state that's
1545 // going to be overwritten by handleTransactionLocked()) outside of
1546 // mStateLock so that the side-effects of the State assignment
1547 // don't happen with mStateLock held (which can cause deadlocks).
1548 State drawingState(mDrawingState);
1549
1550 Mutex::Autolock _l(mStateLock);
1551 const nsecs_t now = systemTime();
1552 mDebugInTransaction = now;
1553
1554 // Here we're guaranteed that some transaction flags are set
1555 // so we can call handleTransactionLocked() unconditionally.
1556 // We call getTransactionFlags(), which will also clear the flags,
1557 // with mStateLock held to guarantee that mCurrentState won't change
1558 // until the transaction is committed.
1559
1560 transactionFlags = getTransactionFlags(eTransactionMask);
1561 handleTransactionLocked(transactionFlags);
1562
1563 mLastTransactionTime = systemTime() - now;
1564 mDebugInTransaction = 0;
1565 invalidateHwcGeometry();
1566 // here the transaction has been committed
1567}
1568
1569void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
1570{
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001571 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001572 mCurrentState.traverseInZOrder([](Layer* layer) {
1573 layer->notifyAvailableFrames();
1574 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001575
1576 /*
1577 * Traversal of the children
1578 * (perform the transaction for each of them if needed)
1579 */
1580
1581 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001582 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001583 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001584 if (!trFlags) return;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001585
1586 const uint32_t flags = layer->doTransaction(0);
1587 if (flags & Layer::eVisibleRegion)
1588 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001589 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001590 }
1591
1592 /*
1593 * Perform display own transactions if needed
1594 */
1595
1596 if (transactionFlags & eDisplayTransactionNeeded) {
1597 // here we take advantage of Vector's copy-on-write semantics to
1598 // improve performance by skipping the transaction entirely when
1599 // know that the lists are identical
1600 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1601 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
1602 if (!curr.isIdenticalTo(draw)) {
1603 mVisibleRegionsDirty = true;
1604 const size_t cc = curr.size();
1605 size_t dc = draw.size();
1606
1607 // find the displays that were removed
1608 // (ie: in drawing state but not in current state)
1609 // also handle displays that changed
1610 // (ie: displays that are in both lists)
1611 for (size_t i=0 ; i<dc ; i++) {
1612 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1613 if (j < 0) {
1614 // in drawing state but not in current state
1615 if (!draw[i].isMainDisplay()) {
1616 // Call makeCurrent() on the primary display so we can
1617 // be sure that nothing associated with this display
1618 // is current.
1619 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
1620 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
1621 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1622 if (hw != NULL)
1623 hw->disconnect(getHwComposer());
1624 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
1625 mEventThread->onHotplugReceived(draw[i].type, false);
1626 mDisplays.removeItem(draw.keyAt(i));
1627 } else {
1628 ALOGW("trying to remove the main display");
1629 }
1630 } else {
1631 // this display is in both lists. see if something changed.
1632 const DisplayDeviceState& state(curr[j]);
1633 const wp<IBinder>& display(curr.keyAt(j));
1634 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1635 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
1636 if (state_binder != draw_binder) {
1637 // changing the surface is like destroying and
1638 // recreating the DisplayDevice, so we just remove it
1639 // from the drawing state, so that it get re-added
1640 // below.
1641 sp<DisplayDevice> hw(getDisplayDevice(display));
1642 if (hw != NULL)
1643 hw->disconnect(getHwComposer());
1644 mDisplays.removeItem(display);
1645 mDrawingState.displays.removeItemsAt(i);
1646 dc--; i--;
1647 // at this point we must loop to the next item
1648 continue;
1649 }
1650
1651 const sp<DisplayDevice> disp(getDisplayDevice(display));
1652 if (disp != NULL) {
1653 if (state.layerStack != draw[i].layerStack) {
1654 disp->setLayerStack(state.layerStack);
1655 }
1656 if ((state.orientation != draw[i].orientation)
1657 || (state.viewport != draw[i].viewport)
1658 || (state.frame != draw[i].frame))
1659 {
1660 disp->setProjection(state.orientation,
1661 state.viewport, state.frame);
1662 }
1663 if (state.width != draw[i].width || state.height != draw[i].height) {
1664 disp->setDisplaySize(state.width, state.height);
1665 }
1666 }
1667 }
1668 }
1669
1670 // find displays that were added
1671 // (ie: in current state but not in drawing state)
1672 for (size_t i=0 ; i<cc ; i++) {
1673 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
1674 const DisplayDeviceState& state(curr[i]);
1675
1676 sp<DisplaySurface> dispSurface;
1677 sp<IGraphicBufferProducer> producer;
1678 sp<IGraphicBufferProducer> bqProducer;
1679 sp<IGraphicBufferConsumer> bqConsumer;
1680 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1681 new GraphicBufferAlloc());
1682
1683 int32_t hwcDisplayId = -1;
1684 if (state.isVirtualDisplay()) {
1685 // Virtual displays without a surface are dormant:
1686 // they have external state (layer stack, projection,
1687 // etc.) but no internal state (i.e. a DisplayDevice).
1688 if (state.surface != NULL) {
1689
1690 int width = 0;
1691 int status = state.surface->query(
1692 NATIVE_WINDOW_WIDTH, &width);
1693 ALOGE_IF(status != NO_ERROR,
1694 "Unable to query width (%d)", status);
1695 int height = 0;
1696 status = state.surface->query(
1697 NATIVE_WINDOW_HEIGHT, &height);
1698 ALOGE_IF(status != NO_ERROR,
1699 "Unable to query height (%d)", status);
1700 if (mUseHwcVirtualDisplays &&
1701 (MAX_VIRTUAL_DISPLAY_DIMENSION == 0 ||
1702 (width <= MAX_VIRTUAL_DISPLAY_DIMENSION &&
1703 height <= MAX_VIRTUAL_DISPLAY_DIMENSION))) {
1704 hwcDisplayId = allocateHwcDisplayId(state.type);
1705 }
1706
1707 sp<VirtualDisplaySurface> vds = new VirtualDisplaySurface(
1708 *mHwc, hwcDisplayId, state.surface,
1709 bqProducer, bqConsumer, state.displayName);
1710
1711 dispSurface = vds;
1712 producer = vds;
1713 }
1714 } else {
1715 ALOGE_IF(state.surface!=NULL,
1716 "adding a supported display, but rendering "
1717 "surface is provided (%p), ignoring it",
1718 state.surface.get());
1719 hwcDisplayId = allocateHwcDisplayId(state.type);
1720 // for supported (by hwc) displays we provide our
1721 // own rendering surface
1722 dispSurface = new FramebufferSurface(*mHwc, state.type,
1723 bqConsumer);
1724 producer = bqProducer;
1725 }
1726
1727 const wp<IBinder>& display(curr.keyAt(i));
1728 if (dispSurface != NULL) {
1729 sp<DisplayDevice> hw = new DisplayDevice(this,
1730 state.type, hwcDisplayId,
1731 mHwc->getFormat(hwcDisplayId), state.isSecure,
1732 display, dispSurface, producer,
1733 mRenderEngine->getEGLConfig());
1734 hw->setLayerStack(state.layerStack);
1735 hw->setProjection(state.orientation,
1736 state.viewport, state.frame);
1737 hw->setDisplayName(state.displayName);
1738 mDisplays.add(display, hw);
1739 if (state.isVirtualDisplay()) {
1740 if (hwcDisplayId >= 0) {
1741 mHwc->setVirtualDisplayProperties(hwcDisplayId,
1742 hw->getWidth(), hw->getHeight(),
1743 hw->getFormat());
1744 }
1745 } else {
1746 mEventThread->onHotplugReceived(state.type, true);
1747 }
1748 }
1749 }
1750 }
1751 }
1752 }
1753
1754 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1755 // The transform hint might have changed for some layers
1756 // (either because a display has changed, or because a layer
1757 // as changed).
1758 //
1759 // Walk through all the layers in currentLayers,
1760 // and update their transform hint.
1761 //
1762 // If a layer is visible only on a single display, then that
1763 // display is used to calculate the hint, otherwise we use the
1764 // default display.
1765 //
1766 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1767 // the hint is set before we acquire a buffer from the surface texture.
1768 //
1769 // NOTE: layer transactions have taken place already, so we use their
1770 // drawing state. However, SurfaceFlinger's own transaction has not
1771 // happened yet, so we must use the current state layer list
1772 // (soon to become the drawing state list).
1773 //
1774 sp<const DisplayDevice> disp;
1775 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08001776 bool first = true;
1777 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001778 // NOTE: we rely on the fact that layers are sorted by
1779 // layerStack first (so we don't have to traverse the list
1780 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07001781 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08001782 if (first || currentlayerStack != layerStack) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001783 currentlayerStack = layerStack;
1784 // figure out if this layerstack is mirrored
1785 // (more than one display) if so, pick the default display,
1786 // if not, pick the only display it's on.
1787 disp.clear();
1788 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1789 sp<const DisplayDevice> hw(mDisplays[dpy]);
1790 if (hw->getLayerStack() == currentlayerStack) {
1791 if (disp == NULL) {
1792 disp = hw;
1793 } else {
1794 disp = NULL;
1795 break;
1796 }
1797 }
1798 }
1799 }
1800 if (disp == NULL) {
1801 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1802 // redraw after transform hint changes. See bug 8508397.
1803
1804 // could be null when this layer is using a layerStack
1805 // that is not visible on any display. Also can occur at
1806 // screen off/on times.
1807 disp = getDefaultDisplayDevice();
1808 }
1809 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08001810
1811 first = false;
1812 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001813 }
1814
1815
1816 /*
1817 * Perform our own transaction if needed
1818 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07001819
1820 if (mLayersAdded) {
1821 mLayersAdded = false;
1822 // Layers have been added.
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001823 mVisibleRegionsDirty = true;
1824 }
1825
1826 // some layers might have been removed, so
1827 // we need to update the regions they're exposing.
1828 if (mLayersRemoved) {
1829 mLayersRemoved = false;
1830 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001831 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001832 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001833 // this layer is not visible anymore
1834 // TODO: we could traverse the tree from front to back and
1835 // compute the actual visible region
1836 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07001837 Region visibleReg;
1838 visibleReg.set(layer->computeScreenBounds());
1839 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001840 }
Robert Carr2047fae2016-11-28 14:09:09 -08001841 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001842 }
1843
1844 commitTransaction();
1845
1846 updateCursorAsync();
1847}
1848
1849void SurfaceFlinger::updateCursorAsync()
1850{
1851 HWComposer& hwc(getHwComposer());
1852 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1853 sp<const DisplayDevice> hw(mDisplays[dpy]);
1854 const int32_t id = hw->getHwcDisplayId();
1855 if (id < 0) {
1856 continue;
1857 }
1858 const Vector< sp<Layer> >& currentLayers(
1859 hw->getVisibleLayersSortedByZ());
1860 const size_t count = currentLayers.size();
1861 HWComposer::LayerListIterator cur = hwc.begin(id);
1862 const HWComposer::LayerListIterator end = hwc.end(id);
1863 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1864 if (cur->getCompositionType() != HWC_CURSOR_OVERLAY) {
1865 continue;
1866 }
1867 const sp<Layer>& layer(currentLayers[i]);
1868 Rect cursorPos = layer->getPosition(hw);
1869 hwc.setCursorPositionAsync(id, cursorPos);
1870 break;
1871 }
1872 }
1873}
1874
1875void SurfaceFlinger::commitTransaction()
1876{
1877 if (!mLayersPendingRemoval.isEmpty()) {
1878 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07001879 for (const auto& l : mLayersPendingRemoval) {
1880 recordBufferingStats(l->getName().string(),
1881 l->getOccupancyHistory(true));
1882 l->onRemoved();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001883 }
1884 mLayersPendingRemoval.clear();
1885 }
1886
1887 // If this transaction is part of a window animation then the next frame
1888 // we composite should be considered an animation as well.
1889 mAnimCompositionPending = mAnimTransactionPending;
1890
1891 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001892 mDrawingState.traverseInZOrder([](Layer* layer) {
1893 layer->commitChildList();
1894 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001895 mTransactionPending = false;
1896 mAnimTransactionPending = false;
1897 mTransactionCV.broadcast();
1898}
1899
Robert Carr2047fae2016-11-28 14:09:09 -08001900void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001901 Region& outDirtyRegion, Region& outOpaqueRegion)
1902{
1903 ATRACE_CALL();
1904
1905 Region aboveOpaqueLayers;
1906 Region aboveCoveredLayers;
1907 Region dirty;
1908
1909 outDirtyRegion.clear();
1910
Robert Carr2047fae2016-11-28 14:09:09 -08001911 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001912 // start with the whole surface at its current location
1913 const Layer::State& s(layer->getDrawingState());
1914
1915 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07001916 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08001917 return;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001918
1919 /*
1920 * opaqueRegion: area of a surface that is fully opaque.
1921 */
1922 Region opaqueRegion;
1923
1924 /*
1925 * visibleRegion: area of a surface that is visible on screen
1926 * and not fully transparent. This is essentially the layer's
1927 * footprint minus the opaque regions above it.
1928 * Areas covered by a translucent surface are considered visible.
1929 */
1930 Region visibleRegion;
1931
1932 /*
1933 * coveredRegion: area of a surface that is covered by all
1934 * visible regions above it (which includes the translucent areas).
1935 */
1936 Region coveredRegion;
1937
1938 /*
1939 * transparentRegion: area of a surface that is hinted to be completely
1940 * transparent. This is only used to tell when the layer has no visible
1941 * non-transparent regions and can be removed from the layer list. It
1942 * does not affect the visibleRegion of this layer or any layers
1943 * beneath it. The hint may not be correct if apps don't respect the
1944 * SurfaceView restrictions (which, sadly, some don't).
1945 */
1946 Region transparentRegion;
1947
1948
1949 // handle hidden surfaces by setting the visible region to empty
1950 if (CC_LIKELY(layer->isVisible())) {
1951 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001952 Rect bounds(layer->computeScreenBounds());
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001953 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001954 Transform tr = layer->getTransform();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001955 if (!visibleRegion.isEmpty()) {
1956 // Remove the transparent area from the visible region
1957 if (translucent) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001958 if (tr.preserveRects()) {
1959 // transform the transparent region
1960 transparentRegion = tr.transform(s.activeTransparentRegion);
1961 } else {
1962 // transformation too complex, can't do the
1963 // transparent region optimization.
1964 transparentRegion.clear();
1965 }
1966 }
1967
1968 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07001969 const int32_t layerOrientation = tr.getOrientation();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001970 if (s.alpha==255 && !translucent &&
1971 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1972 // the opaque region is the layer's footprint
1973 opaqueRegion = visibleRegion;
1974 }
1975 }
1976 }
1977
1978 // Clip the covered region to the visible region
1979 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1980
1981 // Update aboveCoveredLayers for next (lower) layer
1982 aboveCoveredLayers.orSelf(visibleRegion);
1983
1984 // subtract the opaque region covered by the layers above us
1985 visibleRegion.subtractSelf(aboveOpaqueLayers);
1986
1987 // compute this layer's dirty region
1988 if (layer->contentDirty) {
1989 // we need to invalidate the whole region
1990 dirty = visibleRegion;
1991 // as well, as the old visible region
1992 dirty.orSelf(layer->visibleRegion);
1993 layer->contentDirty = false;
1994 } else {
1995 /* compute the exposed region:
1996 * the exposed region consists of two components:
1997 * 1) what's VISIBLE now and was COVERED before
1998 * 2) what's EXPOSED now less what was EXPOSED before
1999 *
2000 * note that (1) is conservative, we start with the whole
2001 * visible region but only keep what used to be covered by
2002 * something -- which mean it may have been exposed.
2003 *
2004 * (2) handles areas that were not covered by anything but got
2005 * exposed because of a resize.
2006 */
2007 const Region newExposed = visibleRegion - coveredRegion;
2008 const Region oldVisibleRegion = layer->visibleRegion;
2009 const Region oldCoveredRegion = layer->coveredRegion;
2010 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2011 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
2012 }
2013 dirty.subtractSelf(aboveOpaqueLayers);
2014
2015 // accumulate to the screen dirty region
2016 outDirtyRegion.orSelf(dirty);
2017
2018 // Update aboveOpaqueLayers for next (lower) layer
2019 aboveOpaqueLayers.orSelf(opaqueRegion);
2020
2021 // Store the visible region in screen space
2022 layer->setVisibleRegion(visibleRegion);
2023 layer->setCoveredRegion(coveredRegion);
2024 layer->setVisibleNonTransparentRegion(
2025 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002026 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002027
2028 outOpaqueRegion = aboveOpaqueLayers;
2029}
2030
2031void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2032 const Region& dirty) {
2033 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2034 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2035 if (hw->getLayerStack() == layerStack) {
2036 hw->dirtyRegion.orSelf(dirty);
2037 }
2038 }
2039}
2040
2041bool SurfaceFlinger::handlePageFlip()
2042{
Brian Andersond6927fb2016-07-23 23:37:30 -07002043 nsecs_t latchTime = systemTime();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002044 Region dirtyRegion;
2045
2046 bool visibleRegions = false;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002047 bool frameQueued = false;
2048
2049 // Store the set of layers that need updates. This set must not change as
2050 // buffers are being latched, as this could result in a deadlock.
2051 // Example: Two producers share the same command stream and:
2052 // 1.) Layer 0 is latched
2053 // 2.) Layer 0 gets a new frame
2054 // 2.) Layer 1 gets a new frame
2055 // 3.) Layer 1 is latched.
2056 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2057 // second frame. But layer 0's second frame could be waiting on display.
2058 Vector<Layer*> layersWithQueuedFrames;
Robert Carr2047fae2016-11-28 14:09:09 -08002059 mDrawingState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002060 if (layer->hasQueuedFrame()) {
2061 frameQueued = true;
2062 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002063 layersWithQueuedFrames.push_back(layer);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002064 } else {
2065 layer->useEmptyDamage();
2066 }
2067 } else {
2068 layer->useEmptyDamage();
2069 }
Robert Carr2047fae2016-11-28 14:09:09 -08002070 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002071 for (size_t i = 0, count = layersWithQueuedFrames.size() ; i<count ; i++) {
2072 Layer* layer = layersWithQueuedFrames[i];
Brian Andersond6927fb2016-07-23 23:37:30 -07002073 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002074 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002075 invalidateLayerStack(layer->getLayerStack(), dirty);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002076 }
2077
2078 mVisibleRegionsDirty |= visibleRegions;
2079
2080 // If we will need to wake up at some time in the future to deal with a
2081 // queued frame that shouldn't be displayed during this vsync period, wake
2082 // up during the next vsync period to check again.
2083 if (frameQueued && layersWithQueuedFrames.empty()) {
2084 signalLayerUpdate();
2085 }
2086
2087 // Only continue with the refresh if there is actually new work to do
2088 return !layersWithQueuedFrames.empty();
2089}
2090
2091void SurfaceFlinger::invalidateHwcGeometry()
2092{
2093 mHwWorkListDirty = true;
2094}
2095
2096
2097void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
2098 const Region& inDirtyRegion)
2099{
2100 // We only need to actually compose the display if:
2101 // 1) It is being handled by hardware composer, which may need this to
2102 // keep its virtual display state machine in sync, or
2103 // 2) There is work to be done (the dirty region isn't empty)
2104 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
2105 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
2106 return;
2107 }
2108
2109 Region dirtyRegion(inDirtyRegion);
2110
2111 // compute the invalid region
2112 hw->swapRegion.orSelf(dirtyRegion);
2113
2114 uint32_t flags = hw->getFlags();
2115 if (flags & DisplayDevice::SWAP_RECTANGLE) {
2116 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2117 // takes a rectangle, we must make sure to update that whole
2118 // rectangle in that case
2119 dirtyRegion.set(hw->swapRegion.bounds());
2120 } else {
2121 if (flags & DisplayDevice::PARTIAL_UPDATES) {
2122 // We need to redraw the rectangle that will be updated
2123 // (pushed to the framebuffer).
2124 // This is needed because PARTIAL_UPDATES only takes one
2125 // rectangle instead of a region (see DisplayDevice::flip())
2126 dirtyRegion.set(hw->swapRegion.bounds());
2127 } else {
2128 // we need to redraw everything (the whole screen)
2129 dirtyRegion.set(hw->bounds());
2130 hw->swapRegion = dirtyRegion;
2131 }
2132 }
2133
2134 if (CC_LIKELY(!mDaltonize && !mHasColorMatrix)) {
2135 if (!doComposeSurfaces(hw, dirtyRegion)) return;
2136 } else {
2137 RenderEngine& engine(getRenderEngine());
2138 mat4 colorMatrix = mColorMatrix;
2139 if (mDaltonize) {
2140 colorMatrix = colorMatrix * mDaltonizer();
2141 }
2142 mat4 oldMatrix = engine.setupColorTransform(colorMatrix);
2143 doComposeSurfaces(hw, dirtyRegion);
2144 engine.setupColorTransform(oldMatrix);
2145 }
2146
2147 // update the swap region and clear the dirty region
2148 hw->swapRegion.orSelf(dirtyRegion);
2149
2150 // swap buffers (presentation)
2151 hw->swapBuffers(getHwComposer());
2152}
2153
2154bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
2155{
2156 RenderEngine& engine(getRenderEngine());
2157 const int32_t id = hw->getHwcDisplayId();
2158 HWComposer& hwc(getHwComposer());
2159 HWComposer::LayerListIterator cur = hwc.begin(id);
2160 const HWComposer::LayerListIterator end = hwc.end(id);
2161
2162 bool hasGlesComposition = hwc.hasGlesComposition(id);
2163 if (hasGlesComposition) {
2164 if (!hw->makeCurrent(mEGLDisplay, mEGLContext)) {
2165 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
2166 hw->getDisplayName().string());
2167 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2168 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2169 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2170 }
2171 return false;
2172 }
2173
2174 // Never touch the framebuffer if we don't have any framebuffer layers
2175 const bool hasHwcComposition = hwc.hasHwcComposition(id);
2176 if (hasHwcComposition) {
2177 // when using overlays, we assume a fully transparent framebuffer
2178 // NOTE: we could reduce how much we need to clear, for instance
2179 // remove where there are opaque FB layers. however, on some
2180 // GPUs doing a "clean slate" clear might be more efficient.
2181 // We'll revisit later if needed.
2182 engine.clearWithColor(0, 0, 0, 0);
2183 } else {
2184 // we start with the whole screen area
2185 const Region bounds(hw->getBounds());
2186
2187 // we remove the scissor part
2188 // we're left with the letterbox region
2189 // (common case is that letterbox ends-up being empty)
2190 const Region letterbox(bounds.subtract(hw->getScissor()));
2191
2192 // compute the area to clear
2193 Region region(hw->undefinedRegion.merge(letterbox));
2194
2195 // but limit it to the dirty region
2196 region.andSelf(dirty);
2197
2198 // screen is already cleared here
2199 if (!region.isEmpty()) {
2200 // can happen with SurfaceView
2201 drawWormhole(hw, region);
2202 }
2203 }
2204
2205 if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
2206 // just to be on the safe side, we don't set the
2207 // scissor on the main display. It should never be needed
2208 // anyways (though in theory it could since the API allows it).
2209 const Rect& bounds(hw->getBounds());
2210 const Rect& scissor(hw->getScissor());
2211 if (scissor != bounds) {
2212 // scissor doesn't match the screen's dimensions, so we
2213 // need to clear everything outside of it and enable
2214 // the GL scissor so we don't draw anything where we shouldn't
2215
2216 // enable scissor for this frame
2217 const uint32_t height = hw->getHeight();
2218 engine.setScissor(scissor.left, height - scissor.bottom,
2219 scissor.getWidth(), scissor.getHeight());
2220 }
2221 }
2222 }
2223
2224 /*
2225 * and then, render the layers targeted at the framebuffer
2226 */
2227
2228 const Vector< sp<Layer> >& layers(hw->getVisibleLayersSortedByZ());
2229 const size_t count = layers.size();
2230 const Transform& tr = hw->getTransform();
2231 if (cur != end) {
2232 // we're using h/w composer
2233 for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
2234 const sp<Layer>& layer(layers[i]);
2235 const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
2236 if (!clip.isEmpty()) {
2237 switch (cur->getCompositionType()) {
2238 case HWC_CURSOR_OVERLAY:
2239 case HWC_OVERLAY: {
2240 const Layer::State& state(layer->getDrawingState());
2241 if ((cur->getHints() & HWC_HINT_CLEAR_FB)
2242 && i
2243 && layer->isOpaque(state) && (state.alpha == 0xFF)
2244 && hasGlesComposition) {
2245 // never clear the very first layer since we're
2246 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002247 layer->clearWithOpenGL(hw);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002248 }
2249 break;
2250 }
2251 case HWC_FRAMEBUFFER: {
2252 layer->draw(hw, clip);
2253 break;
2254 }
2255 case HWC_FRAMEBUFFER_TARGET: {
2256 // this should not happen as the iterator shouldn't
2257 // let us get there.
2258 ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%zu)", i);
2259 break;
2260 }
2261 }
2262 }
2263 layer->setAcquireFence(hw, *cur);
2264 }
2265 } else {
2266 // we're not using h/w composer
2267 for (size_t i=0 ; i<count ; ++i) {
2268 const sp<Layer>& layer(layers[i]);
2269 const Region clip(dirty.intersect(
2270 tr.transform(layer->visibleRegion)));
2271 if (!clip.isEmpty()) {
2272 layer->draw(hw, clip);
2273 }
2274 }
2275 }
2276
2277 // disable scissor at the end of the frame
2278 engine.disableScissor();
2279 return true;
2280}
2281
2282void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
2283 const int32_t height = hw->getHeight();
2284 RenderEngine& engine(getRenderEngine());
2285 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
2286}
2287
2288status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
2289 const sp<IBinder>& handle,
2290 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002291 const sp<Layer>& lbc,
2292 const sp<Layer>& parent)
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002293{
2294 // add this layer to the current state list
2295 {
2296 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002297 if (mNumLayers >= MAX_LAYERS) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002298 return NO_MEMORY;
2299 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002300 if (parent == nullptr) {
2301 mCurrentState.layersSortedByZ.add(lbc);
2302 } else {
2303 parent->addChild(lbc);
2304 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002305 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002306 mLayersAdded = true;
2307 mNumLayers++;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002308 }
2309
2310 // attach this layer to the client
2311 client->attachLayer(handle, lbc);
2312
2313 return NO_ERROR;
2314}
2315
2316status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) {
2317 Mutex::Autolock _l(mStateLock);
2318 sp<Layer> layer = weakLayer.promote();
2319 if (layer == nullptr) {
2320 // The layer has already been removed, carry on
2321 return NO_ERROR;
2322 }
2323
Robert Carr1f0a16a2016-10-24 16:27:39 -07002324 const auto& p = layer->getParent();
2325 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2326 mCurrentState.layersSortedByZ.remove(layer);
2327
2328 if (index < 0) {
2329 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2330 layer->getName().string(),
2331 (p != nullptr) ? p->getName().string() : "no-parent");
2332 return BAD_VALUE;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002333 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002334
2335 mLayersPendingRemoval.add(layer);
2336 mLayersRemoved = true;
2337 mNumLayers--;
2338 setTransactionFlags(eTransactionNeeded);
2339 return NO_ERROR;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002340}
2341
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002342uint32_t SurfaceFlinger::peekTransactionFlags() {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002343 return android_atomic_release_load(&mTransactionFlags);
2344}
2345
2346uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
2347 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2348}
2349
2350uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
2351 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2352 if ((old & flags)==0) { // wake the server up
2353 signalTransaction();
2354 }
2355 return old;
2356}
2357
2358void SurfaceFlinger::setTransactionState(
2359 const Vector<ComposerState>& state,
2360 const Vector<DisplayState>& displays,
2361 uint32_t flags)
2362{
2363 ATRACE_CALL();
2364 Mutex::Autolock _l(mStateLock);
2365 uint32_t transactionFlags = 0;
2366
2367 if (flags & eAnimation) {
2368 // For window updates that are part of an animation we must wait for
2369 // previous animation "frames" to be handled.
2370 while (mAnimTransactionPending) {
2371 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2372 if (CC_UNLIKELY(err != NO_ERROR)) {
2373 // just in case something goes wrong in SF, return to the
2374 // caller after a few seconds.
2375 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2376 "waiting for previous animation frame");
2377 mAnimTransactionPending = false;
2378 break;
2379 }
2380 }
2381 }
2382
2383 size_t count = displays.size();
2384 for (size_t i=0 ; i<count ; i++) {
2385 const DisplayState& s(displays[i]);
2386 transactionFlags |= setDisplayStateLocked(s);
2387 }
2388
2389 count = state.size();
2390 for (size_t i=0 ; i<count ; i++) {
2391 const ComposerState& s(state[i]);
2392 // Here we need to check that the interface we're given is indeed
2393 // one of our own. A malicious client could give us a NULL
2394 // IInterface, or one of its own or even one of our own but a
2395 // different type. All these situations would cause us to crash.
2396 //
2397 // NOTE: it would be better to use RTTI as we could directly check
2398 // that we have a Client*. however, RTTI is disabled in Android.
2399 if (s.client != NULL) {
2400 sp<IBinder> binder = IInterface::asBinder(s.client);
2401 if (binder != NULL) {
Fabien Sanglard45b20252017-01-18 16:43:18 -08002402 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002403 sp<Client> client( static_cast<Client *>(s.client.get()) );
2404 transactionFlags |= setClientStateLocked(client, s.state);
2405 }
2406 }
2407 }
2408 }
2409
2410 // If a synchronous transaction is explicitly requested without any changes,
2411 // force a transaction anyway. This can be used as a flush mechanism for
2412 // previous async transactions.
2413 if (transactionFlags == 0 && (flags & eSynchronous)) {
2414 transactionFlags = eTransactionNeeded;
2415 }
2416
2417 if (transactionFlags) {
2418 if (mInterceptor.isEnabled()) {
2419 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2420 }
2421
2422 // this triggers the transaction
2423 setTransactionFlags(transactionFlags);
2424
2425 // if this is a synchronous transaction, wait for it to take effect
2426 // before returning.
2427 if (flags & eSynchronous) {
2428 mTransactionPending = true;
2429 }
2430 if (flags & eAnimation) {
2431 mAnimTransactionPending = true;
2432 }
2433 while (mTransactionPending) {
2434 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2435 if (CC_UNLIKELY(err != NO_ERROR)) {
2436 // just in case something goes wrong in SF, return to the
2437 // called after a few seconds.
2438 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2439 mTransactionPending = false;
2440 break;
2441 }
2442 }
2443 }
2444}
2445
2446uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2447{
2448 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2449 if (dpyIdx < 0)
2450 return 0;
2451
2452 uint32_t flags = 0;
2453 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
2454 if (disp.isValid()) {
2455 const uint32_t what = s.what;
2456 if (what & DisplayState::eSurfaceChanged) {
2457 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
2458 disp.surface = s.surface;
2459 flags |= eDisplayTransactionNeeded;
2460 }
2461 }
2462 if (what & DisplayState::eLayerStackChanged) {
2463 if (disp.layerStack != s.layerStack) {
2464 disp.layerStack = s.layerStack;
2465 flags |= eDisplayTransactionNeeded;
2466 }
2467 }
2468 if (what & DisplayState::eDisplayProjectionChanged) {
2469 if (disp.orientation != s.orientation) {
2470 disp.orientation = s.orientation;
2471 flags |= eDisplayTransactionNeeded;
2472 }
2473 if (disp.frame != s.frame) {
2474 disp.frame = s.frame;
2475 flags |= eDisplayTransactionNeeded;
2476 }
2477 if (disp.viewport != s.viewport) {
2478 disp.viewport = s.viewport;
2479 flags |= eDisplayTransactionNeeded;
2480 }
2481 }
2482 if (what & DisplayState::eDisplaySizeChanged) {
2483 if (disp.width != s.width) {
2484 disp.width = s.width;
2485 flags |= eDisplayTransactionNeeded;
2486 }
2487 if (disp.height != s.height) {
2488 disp.height = s.height;
2489 flags |= eDisplayTransactionNeeded;
2490 }
2491 }
2492 }
2493 return flags;
2494}
2495
2496uint32_t SurfaceFlinger::setClientStateLocked(
2497 const sp<Client>& client,
2498 const layer_state_t& s)
2499{
2500 uint32_t flags = 0;
2501 sp<Layer> layer(client->getLayerUser(s.surface));
2502 if (layer != 0) {
2503 const uint32_t what = s.what;
2504 bool geometryAppliesWithResize =
2505 what & layer_state_t::eGeometryAppliesWithResize;
2506 if (what & layer_state_t::ePositionChanged) {
2507 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
2508 flags |= eTraversalNeeded;
2509 }
2510 }
2511 if (what & layer_state_t::eLayerChanged) {
2512 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002513 const auto& p = layer->getParent();
2514 if (p == nullptr) {
2515 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2516 if (layer->setLayer(s.z) && idx >= 0) {
2517 mCurrentState.layersSortedByZ.removeAt(idx);
2518 mCurrentState.layersSortedByZ.add(layer);
2519 // we need traversal (state changed)
2520 // AND transaction (list changed)
2521 flags |= eTransactionNeeded|eTraversalNeeded;
2522 }
2523 } else {
2524 if (p->setChildLayer(layer, s.z)) {
2525 flags |= eTransactionNeeded|eTraversalNeeded;
2526 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002527 }
2528 }
2529 if (what & layer_state_t::eSizeChanged) {
2530 if (layer->setSize(s.w, s.h)) {
2531 flags |= eTraversalNeeded;
2532 }
2533 }
2534 if (what & layer_state_t::eAlphaChanged) {
2535 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
2536 flags |= eTraversalNeeded;
2537 }
2538 if (what & layer_state_t::eMatrixChanged) {
2539 if (layer->setMatrix(s.matrix))
2540 flags |= eTraversalNeeded;
2541 }
2542 if (what & layer_state_t::eTransparentRegionChanged) {
2543 if (layer->setTransparentRegionHint(s.transparentRegion))
2544 flags |= eTraversalNeeded;
2545 }
2546 if (what & layer_state_t::eFlagsChanged) {
2547 if (layer->setFlags(s.flags, s.mask))
2548 flags |= eTraversalNeeded;
2549 }
2550 if (what & layer_state_t::eCropChanged) {
2551 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
2552 flags |= eTraversalNeeded;
2553 }
2554 if (what & layer_state_t::eFinalCropChanged) {
2555 if (layer->setFinalCrop(s.finalCrop))
2556 flags |= eTraversalNeeded;
2557 }
2558 if (what & layer_state_t::eLayerStackChanged) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002559 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002560 // We only allow setting layer stacks for top level layers,
2561 // everything else inherits layer stack from its parent.
2562 if (layer->hasParent()) {
2563 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2564 layer->getName().string());
2565 } else if (idx < 0) {
2566 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2567 "that also does not appear in the top level layer list. Something"
2568 " has gone wrong.", layer->getName().string());
2569 } else if (layer->setLayerStack(s.layerStack)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002570 mCurrentState.layersSortedByZ.removeAt(idx);
2571 mCurrentState.layersSortedByZ.add(layer);
2572 // we need traversal (state changed)
2573 // AND transaction (list changed)
2574 flags |= eTransactionNeeded|eTraversalNeeded;
2575 }
2576 }
2577 if (what & layer_state_t::eDeferTransaction) {
2578 layer->deferTransactionUntil(s.handle, s.frameNumber);
2579 // We don't trigger a traversal here because if no other state is
2580 // changed, we don't want this to cause any more work
2581 }
Robert Carr1db73f62016-12-21 12:58:51 -08002582 if (what & layer_state_t::eReparentChildren) {
2583 if (layer->reparentChildren(s.reparentHandle)) {
2584 flags |= eTransactionNeeded|eTraversalNeeded;
2585 }
2586 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002587 if (what & layer_state_t::eOverrideScalingModeChanged) {
2588 layer->setOverrideScalingMode(s.overrideScalingMode);
2589 // We don't trigger a traversal here because if no other state is
2590 // changed, we don't want this to cause any more work
2591 }
2592 }
2593 return flags;
2594}
2595
2596status_t SurfaceFlinger::createLayer(
2597 const String8& name,
2598 const sp<Client>& client,
2599 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002600 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2601 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002602{
2603 if (int32_t(w|h) < 0) {
2604 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
2605 int(w), int(h));
2606 return BAD_VALUE;
2607 }
2608
2609 status_t result = NO_ERROR;
2610
2611 sp<Layer> layer;
2612
2613 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2614 case ISurfaceComposerClient::eFXSurfaceNormal:
2615 result = createNormalLayer(client,
2616 name, w, h, flags, format,
2617 handle, gbp, &layer);
2618 break;
2619 case ISurfaceComposerClient::eFXSurfaceDim:
2620 result = createDimLayer(client,
2621 name, w, h, flags,
2622 handle, gbp, &layer);
2623 break;
2624 default:
2625 result = BAD_VALUE;
2626 break;
2627 }
2628
2629 if (result != NO_ERROR) {
2630 return result;
2631 }
2632
Albert Chaulk479c60c2017-01-27 14:21:34 -05002633 layer->setInfo(windowType, ownerUid);
2634
Robert Carr1f0a16a2016-10-24 16:27:39 -07002635 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002636 if (result != NO_ERROR) {
2637 return result;
2638 }
2639 mInterceptor.saveSurfaceCreation(layer);
2640
2641 setTransactionFlags(eTransactionNeeded);
2642 return result;
2643}
2644
2645status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2646 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2647 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2648{
2649 // initialize the surfaces
2650 switch (format) {
2651 case PIXEL_FORMAT_TRANSPARENT:
2652 case PIXEL_FORMAT_TRANSLUCENT:
2653 format = PIXEL_FORMAT_RGBA_8888;
2654 break;
2655 case PIXEL_FORMAT_OPAQUE:
2656 format = PIXEL_FORMAT_RGBX_8888;
2657 break;
2658 }
2659
2660 *outLayer = new Layer(this, client, name, w, h, flags);
2661 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2662 if (err == NO_ERROR) {
2663 *handle = (*outLayer)->getHandle();
2664 *gbp = (*outLayer)->getProducer();
2665 }
2666
2667 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2668 return err;
2669}
2670
2671status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2672 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2673 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2674{
2675 *outLayer = new LayerDim(this, client, name, w, h, flags);
2676 *handle = (*outLayer)->getHandle();
2677 *gbp = (*outLayer)->getProducer();
2678 return NO_ERROR;
2679}
2680
2681status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
2682{
2683 // called by the window manager when it wants to remove a Layer
2684 status_t err = NO_ERROR;
2685 sp<Layer> l(client->getLayerUser(handle));
2686 if (l != NULL) {
2687 mInterceptor.saveSurfaceDeletion(l);
2688 err = removeLayer(l);
2689 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2690 "error removing layer=%p (%s)", l.get(), strerror(-err));
2691 }
2692 return err;
2693}
2694
2695status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
2696{
2697 // called by ~LayerCleaner() when all references to the IBinder (handle)
2698 // are gone
2699 return removeLayer(layer);
2700}
2701
2702// ---------------------------------------------------------------------------
2703
2704void SurfaceFlinger::onInitializeDisplays() {
2705 // reset screen orientation and use primary layer stack
2706 Vector<ComposerState> state;
2707 Vector<DisplayState> displays;
2708 DisplayState d;
2709 d.what = DisplayState::eDisplayProjectionChanged |
2710 DisplayState::eLayerStackChanged;
2711 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
2712 d.layerStack = 0;
2713 d.orientation = DisplayState::eOrientationDefault;
2714 d.frame.makeInvalid();
2715 d.viewport.makeInvalid();
2716 d.width = 0;
2717 d.height = 0;
2718 displays.add(d);
2719 setTransactionState(state, displays, 0);
2720 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
2721
2722 const nsecs_t period =
2723 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2724 mAnimFrameTracker.setDisplayRefreshPeriod(period);
2725}
2726
2727void SurfaceFlinger::initializeDisplays() {
2728 class MessageScreenInitialized : public MessageBase {
2729 SurfaceFlinger* flinger;
2730 public:
2731 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2732 virtual bool handler() {
2733 flinger->onInitializeDisplays();
2734 return true;
2735 }
2736 };
2737 sp<MessageBase> msg = new MessageScreenInitialized(this);
2738 postMessageAsync(msg); // we may be called from main thread, use async message
2739}
2740
2741void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2742 int mode) {
2743 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2744 this);
2745 int32_t type = hw->getDisplayType();
2746 int currentMode = hw->getPowerMode();
2747
2748 if (mode == currentMode) {
2749 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
2750 return;
2751 }
2752
2753 hw->setPowerMode(mode);
2754 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2755 ALOGW("Trying to set power mode for virtual display");
2756 return;
2757 }
2758
2759 if (mInterceptor.isEnabled()) {
2760 Mutex::Autolock _l(mStateLock);
2761 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
2762 if (idx < 0) {
2763 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
2764 return;
2765 }
2766 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
2767 }
2768
2769 if (currentMode == HWC_POWER_MODE_OFF) {
2770 // Turn on the display
2771 getHwComposer().setPowerMode(type, mode);
2772 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2773 // FIXME: eventthread only knows about the main display right now
2774 mEventThread->onScreenAcquired();
2775 resyncToHardwareVsync(true);
2776 }
2777
2778 mVisibleRegionsDirty = true;
2779 mHasPoweredOff = true;
2780 repaintEverything();
2781
2782 struct sched_param param = {0};
2783 param.sched_priority = 1;
2784 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
2785 ALOGW("Couldn't set SCHED_FIFO on display on");
2786 }
2787 } else if (mode == HWC_POWER_MODE_OFF) {
2788 // Turn off the display
2789 struct sched_param param = {0};
2790 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
2791 ALOGW("Couldn't set SCHED_OTHER on display off");
2792 }
2793
2794 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2795 disableHardwareVsync(true); // also cancels any in-progress resync
2796
2797 // FIXME: eventthread only knows about the main display right now
2798 mEventThread->onScreenReleased();
2799 }
2800
2801 getHwComposer().setPowerMode(type, mode);
2802 mVisibleRegionsDirty = true;
2803 // from this point on, SF will stop drawing on this display
2804 } else {
2805 getHwComposer().setPowerMode(type, mode);
2806 }
2807}
2808
2809void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2810 class MessageSetPowerMode: public MessageBase {
2811 SurfaceFlinger& mFlinger;
2812 sp<IBinder> mDisplay;
2813 int mMode;
2814 public:
2815 MessageSetPowerMode(SurfaceFlinger& flinger,
2816 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2817 mDisplay(disp) { mMode = mode; }
2818 virtual bool handler() {
2819 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2820 if (hw == NULL) {
2821 ALOGE("Attempt to set power mode = %d for null display %p",
2822 mMode, mDisplay.get());
2823 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2824 ALOGW("Attempt to set power mode = %d for virtual display",
2825 mMode);
2826 } else {
2827 mFlinger.setPowerModeInternal(hw, mMode);
2828 }
2829 return true;
2830 }
2831 };
2832 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
2833 postMessageSync(msg);
2834}
2835
2836// ---------------------------------------------------------------------------
2837
2838status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2839{
2840 String8 result;
2841
2842 IPCThreadState* ipc = IPCThreadState::self();
2843 const int pid = ipc->getCallingPid();
2844 const int uid = ipc->getCallingUid();
2845 if ((uid != AID_SHELL) &&
2846 !PermissionCache::checkPermission(sDump, pid, uid)) {
2847 result.appendFormat("Permission Denial: "
2848 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
2849 } else {
2850 // Try to get the main lock, but give up after one second
2851 // (this would indicate SF is stuck, but we want to be able to
2852 // print something in dumpsys).
2853 status_t err = mStateLock.timedLock(s2ns(1));
2854 bool locked = (err == NO_ERROR);
2855 if (!locked) {
2856 result.appendFormat(
2857 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2858 "dumping anyways (no locks held)\n", strerror(-err), err);
2859 }
2860
2861 bool dumpAll = true;
2862 size_t index = 0;
2863 size_t numArgs = args.size();
2864 if (numArgs) {
2865 if ((index < numArgs) &&
2866 (args[index] == String16("--list"))) {
2867 index++;
2868 listLayersLocked(args, index, result);
2869 dumpAll = false;
2870 }
2871
2872 if ((index < numArgs) &&
2873 (args[index] == String16("--latency"))) {
2874 index++;
2875 dumpStatsLocked(args, index, result);
2876 dumpAll = false;
2877 }
2878
2879 if ((index < numArgs) &&
2880 (args[index] == String16("--latency-clear"))) {
2881 index++;
2882 clearStatsLocked(args, index, result);
2883 dumpAll = false;
2884 }
2885
2886 if ((index < numArgs) &&
2887 (args[index] == String16("--dispsync"))) {
2888 index++;
2889 mPrimaryDispSync.dump(result);
2890 dumpAll = false;
2891 }
2892
2893 if ((index < numArgs) &&
2894 (args[index] == String16("--static-screen"))) {
2895 index++;
2896 dumpStaticScreenStats(result);
2897 dumpAll = false;
2898 }
2899
2900 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07002901 (args[index] == String16("--frame-events"))) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002902 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07002903 dumpFrameEventsLocked(result);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002904 dumpAll = false;
2905 }
2906 }
2907
2908 if (dumpAll) {
2909 dumpAllLocked(args, index, result);
2910 }
2911
2912 if (locked) {
2913 mStateLock.unlock();
2914 }
2915 }
2916 write(fd, result.string(), result.size());
2917 return NO_ERROR;
2918}
2919
2920void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2921 size_t& /* index */, String8& result) const
2922{
Robert Carr2047fae2016-11-28 14:09:09 -08002923 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002924 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08002925 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002926}
2927
2928void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2929 String8& result) const
2930{
2931 String8 name;
2932 if (index < args.size()) {
2933 name = String8(args[index]);
2934 index++;
2935 }
2936
2937 const nsecs_t period =
2938 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2939 result.appendFormat("%" PRId64 "\n", period);
2940
2941 if (name.isEmpty()) {
2942 mAnimFrameTracker.dumpStats(result);
2943 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08002944 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002945 if (name == layer->getName()) {
2946 layer->dumpFrameStats(result);
2947 }
Robert Carr2047fae2016-11-28 14:09:09 -08002948 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002949 }
2950}
2951
2952void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2953 String8& /* result */)
2954{
2955 String8 name;
2956 if (index < args.size()) {
2957 name = String8(args[index]);
2958 index++;
2959 }
2960
Robert Carr2047fae2016-11-28 14:09:09 -08002961 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002962 if (name.isEmpty() || (name == layer->getName())) {
2963 layer->clearFrameStats();
2964 }
Robert Carr2047fae2016-11-28 14:09:09 -08002965 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002966
2967 mAnimFrameTracker.clearStats();
2968}
2969
2970// This should only be called from the main thread. Otherwise it would need
2971// the lock and should use mCurrentState rather than mDrawingState.
2972void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08002973 mDrawingState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002974 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08002975 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002976
2977 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2978}
2979
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002980void SurfaceFlinger::appendSfConfigString(String8& result) const
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002981{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002982 result.append(" [sf");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002983#ifdef HAS_CONTEXT_PRIORITY
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002984 result.append(" HAS_CONTEXT_PRIORITY");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002985#endif
2986#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002987 result.append(" NEVER_DEFAULT_TO_ASYNC_MODE");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002988#endif
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002989 if (isLayerTripleBufferingDisabled())
2990 result.append(" DISABLE_TRIPLE_BUFFERING");
2991 result.append("]");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002992}
2993
2994void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2995{
2996 result.appendFormat("Static screen stats:\n");
2997 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2998 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2999 float percent = 100.0f *
3000 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3001 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3002 b + 1, bucketTimeSec, percent);
3003 }
3004 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3005 float percent = 100.0f *
3006 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3007 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3008 NUM_BUCKETS - 1, bucketTimeSec, percent);
3009}
3010
Brian Andersond6927fb2016-07-23 23:37:30 -07003011void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3012 result.appendFormat("Layer frame timestamps:\n");
3013
3014 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3015 const size_t count = currentLayers.size();
3016 for (size_t i=0 ; i<count ; i++) {
3017 currentLayers[i]->dumpFrameEvents(result);
3018 }
3019}
3020
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003021void SurfaceFlinger::recordBufferingStats(const char* layerName,
3022 std::vector<OccupancyTracker::Segment>&& history) {
3023 Mutex::Autolock lock(mBufferingStatsMutex);
3024 auto& stats = mBufferingStats[layerName];
3025 for (const auto& segment : history) {
3026 if (!segment.usedThirdBuffer) {
3027 stats.twoBufferTime += segment.totalTime;
3028 }
3029 if (segment.occupancyAverage < 1.0f) {
3030 stats.doubleBufferedTime += segment.totalTime;
3031 } else if (segment.occupancyAverage < 2.0f) {
3032 stats.tripleBufferedTime += segment.totalTime;
3033 }
3034 ++stats.numSegments;
3035 stats.totalTime += segment.totalTime;
3036 }
3037}
3038
3039void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3040 result.append("Buffering stats:\n");
3041 result.append(" [Layer name] <Active time> <Two buffer> "
3042 "<Double buffered> <Triple buffered>\n");
3043 Mutex::Autolock lock(mBufferingStatsMutex);
3044 typedef std::tuple<std::string, float, float, float> BufferTuple;
3045 std::map<float, BufferTuple, std::greater<float>> sorted;
3046 for (const auto& statsPair : mBufferingStats) {
3047 const char* name = statsPair.first.c_str();
3048 const BufferingStats& stats = statsPair.second;
3049 if (stats.numSegments == 0) {
3050 continue;
3051 }
3052 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3053 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3054 stats.totalTime;
3055 float doubleBufferRatio = static_cast<float>(
3056 stats.doubleBufferedTime) / stats.totalTime;
3057 float tripleBufferRatio = static_cast<float>(
3058 stats.tripleBufferedTime) / stats.totalTime;
3059 sorted.insert({activeTime, {name, twoBufferRatio,
3060 doubleBufferRatio, tripleBufferRatio}});
3061 }
3062 for (const auto& sortedPair : sorted) {
3063 float activeTime = sortedPair.first;
3064 const BufferTuple& values = sortedPair.second;
3065 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3066 std::get<0>(values).c_str(), activeTime,
3067 std::get<1>(values), std::get<2>(values),
3068 std::get<3>(values));
3069 }
3070 result.append("\n");
3071}
3072
3073void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3074 String8& result) const
3075{
3076 bool colorize = false;
3077 if (index < args.size()
3078 && (args[index] == String16("--color"))) {
3079 colorize = true;
3080 index++;
3081 }
3082
3083 Colorizer colorizer(colorize);
3084
3085 // figure out if we're stuck somewhere
3086 const nsecs_t now = systemTime();
3087 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3088 const nsecs_t inTransaction(mDebugInTransaction);
3089 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3090 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3091
3092 /*
3093 * Dump library configuration.
3094 */
3095
3096 colorizer.bold(result);
3097 result.append("Build configuration:");
3098 colorizer.reset(result);
3099 appendSfConfigString(result);
3100 appendUiConfigString(result);
3101 appendGuiConfigString(result);
3102 result.append("\n");
3103
3104 colorizer.bold(result);
3105 result.append("Sync configuration: ");
3106 colorizer.reset(result);
3107 result.append(SyncFeatures::getInstance().toString());
3108 result.append("\n");
3109
3110 colorizer.bold(result);
3111 result.append("DispSync configuration: ");
3112 colorizer.reset(result);
3113 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3114 "present offset %d ns (refresh %" PRId64 " ns)",
3115 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, PRESENT_TIME_OFFSET_FROM_VSYNC_NS,
3116 mHwc->getRefreshPeriod(HWC_DISPLAY_PRIMARY));
3117 result.append("\n");
3118
3119 // Dump static screen stats
3120 result.append("\n");
3121 dumpStaticScreenStats(result);
3122 result.append("\n");
3123
3124 dumpBufferingStats(result);
3125
3126 /*
3127 * Dump the visible layer list
3128 */
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003129 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003130 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003131 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003132 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003133 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003134 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003135
3136 /*
3137 * Dump Display state
3138 */
3139
3140 colorizer.bold(result);
3141 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
3142 colorizer.reset(result);
3143 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3144 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
3145 hw->dump(result);
3146 }
3147
3148 /*
3149 * Dump SurfaceFlinger global state
3150 */
3151
3152 colorizer.bold(result);
3153 result.append("SurfaceFlinger global state:\n");
3154 colorizer.reset(result);
3155
3156 HWComposer& hwc(getHwComposer());
3157 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3158
3159 colorizer.bold(result);
3160 result.appendFormat("EGL implementation : %s\n",
3161 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3162 colorizer.reset(result);
3163 result.appendFormat("%s\n",
3164 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
3165
3166 mRenderEngine->dump(result);
3167
3168 hw->undefinedRegion.dump(result, "undefinedRegion");
3169 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3170 hw->getOrientation(), hw->isDisplayOn());
3171 result.appendFormat(
3172 " last eglSwapBuffers() time: %f us\n"
3173 " last transaction time : %f us\n"
3174 " transaction-flags : %08x\n"
3175 " refresh-rate : %f fps\n"
3176 " x-dpi : %f\n"
3177 " y-dpi : %f\n"
3178 " gpu_to_cpu_unsupported : %d\n"
3179 ,
3180 mLastSwapBufferTime/1000.0,
3181 mLastTransactionTime/1000.0,
3182 mTransactionFlags,
3183 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
3184 hwc.getDpiX(HWC_DISPLAY_PRIMARY),
3185 hwc.getDpiY(HWC_DISPLAY_PRIMARY),
3186 !mGpuToCpuSupported);
3187
3188 result.appendFormat(" eglSwapBuffers time: %f us\n",
3189 inSwapBuffersDuration/1000.0);
3190
3191 result.appendFormat(" transaction time: %f us\n",
3192 inTransactionDuration/1000.0);
3193
3194 /*
3195 * VSYNC state
3196 */
3197 mEventThread->dump(result);
3198
3199 /*
3200 * Dump HWComposer state
3201 */
3202 colorizer.bold(result);
3203 result.append("h/w composer state:\n");
3204 colorizer.reset(result);
3205 result.appendFormat(" h/w composer %s and %s\n",
3206 hwc.initCheck()==NO_ERROR ? "present" : "not present",
3207 (mDebugDisableHWC || mDebugRegion || mDaltonize
3208 || mHasColorMatrix) ? "disabled" : "enabled");
3209 hwc.dump(result);
3210
3211 /*
3212 * Dump gralloc state
3213 */
3214 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3215 alloc.dump(result);
3216}
3217
3218const Vector< sp<Layer> >&
3219SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
3220 // Note: mStateLock is held here
3221 wp<IBinder> dpy;
3222 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3223 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3224 dpy = mDisplays.keyAt(i);
3225 break;
3226 }
3227 }
3228 if (dpy == NULL) {
3229 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3230 // Just use the primary display so we have something to return
3231 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3232 }
3233 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
3234}
3235
3236bool SurfaceFlinger::startDdmConnection()
3237{
3238 void* libddmconnection_dso =
3239 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3240 if (!libddmconnection_dso) {
3241 return false;
3242 }
3243 void (*DdmConnection_start)(const char* name);
3244 DdmConnection_start =
3245 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
3246 if (!DdmConnection_start) {
3247 dlclose(libddmconnection_dso);
3248 return false;
3249 }
3250 (*DdmConnection_start)(getServiceName());
3251 return true;
3252}
3253
3254status_t SurfaceFlinger::onTransact(
3255 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3256{
3257 switch (code) {
3258 case CREATE_CONNECTION:
3259 case CREATE_DISPLAY:
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003260 case BOOT_FINISHED:
3261 case CLEAR_ANIMATION_FRAME_STATS:
3262 case GET_ANIMATION_FRAME_STATS:
3263 case SET_POWER_MODE:
3264 case GET_HDR_CAPABILITIES:
3265 {
3266 // codes that require permission check
3267 IPCThreadState* ipc = IPCThreadState::self();
3268 const int pid = ipc->getCallingPid();
3269 const int uid = ipc->getCallingUid();
3270 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3271 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3272 ALOGE("Permission Denial: "
3273 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3274 return PERMISSION_DENIED;
3275 }
3276 break;
3277 }
Robert Carr1db73f62016-12-21 12:58:51 -08003278 /*
3279 * Calling setTransactionState is safe, because you need to have been
3280 * granted a reference to Client* and Handle* to do anything with it.
3281 *
3282 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3283 */
3284 case SET_TRANSACTION_STATE:
3285 case CREATE_SCOPED_CONNECTION:
3286 {
3287 break;
3288 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003289 case CAPTURE_SCREEN:
3290 {
3291 // codes that require permission check
3292 IPCThreadState* ipc = IPCThreadState::self();
3293 const int pid = ipc->getCallingPid();
3294 const int uid = ipc->getCallingUid();
3295 if ((uid != AID_GRAPHICS) &&
3296 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
3297 ALOGE("Permission Denial: "
3298 "can't read framebuffer pid=%d, uid=%d", pid, uid);
3299 return PERMISSION_DENIED;
3300 }
3301 break;
3302 }
3303 }
3304
3305 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3306 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
3307 CHECK_INTERFACE(ISurfaceComposer, data, reply);
3308 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
3309 IPCThreadState* ipc = IPCThreadState::self();
3310 const int pid = ipc->getCallingPid();
3311 const int uid = ipc->getCallingUid();
3312 ALOGE("Permission Denial: "
3313 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3314 return PERMISSION_DENIED;
3315 }
3316 int n;
3317 switch (code) {
3318 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
3319 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
3320 return NO_ERROR;
3321 case 1002: // SHOW_UPDATES
3322 n = data.readInt32();
3323 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
3324 invalidateHwcGeometry();
3325 repaintEverything();
3326 return NO_ERROR;
3327 case 1004:{ // repaint everything
3328 repaintEverything();
3329 return NO_ERROR;
3330 }
3331 case 1005:{ // force transaction
3332 setTransactionFlags(
3333 eTransactionNeeded|
3334 eDisplayTransactionNeeded|
3335 eTraversalNeeded);
3336 return NO_ERROR;
3337 }
3338 case 1006:{ // send empty update
3339 signalRefresh();
3340 return NO_ERROR;
3341 }
3342 case 1008: // toggle use of hw composer
3343 n = data.readInt32();
3344 mDebugDisableHWC = n ? 1 : 0;
3345 invalidateHwcGeometry();
3346 repaintEverything();
3347 return NO_ERROR;
3348 case 1009: // toggle use of transform hint
3349 n = data.readInt32();
3350 mDebugDisableTransformHint = n ? 1 : 0;
3351 invalidateHwcGeometry();
3352 repaintEverything();
3353 return NO_ERROR;
3354 case 1010: // interrogate.
3355 reply->writeInt32(0);
3356 reply->writeInt32(0);
3357 reply->writeInt32(mDebugRegion);
3358 reply->writeInt32(0);
3359 reply->writeInt32(mDebugDisableHWC);
3360 return NO_ERROR;
3361 case 1013: {
3362 Mutex::Autolock _l(mStateLock);
3363 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3364 reply->writeInt32(hw->getPageFlipCount());
3365 return NO_ERROR;
3366 }
3367 case 1014: {
3368 // daltonize
3369 n = data.readInt32();
3370 switch (n % 10) {
3371 case 1:
3372 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3373 break;
3374 case 2:
3375 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3376 break;
3377 case 3:
3378 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3379 break;
3380 }
3381 if (n >= 10) {
3382 mDaltonizer.setMode(ColorBlindnessMode::Correction);
3383 } else {
3384 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
3385 }
3386 mDaltonize = n > 0;
3387 invalidateHwcGeometry();
3388 repaintEverything();
3389 return NO_ERROR;
3390 }
3391 case 1015: {
3392 // apply a color matrix
3393 n = data.readInt32();
3394 mHasColorMatrix = n ? 1 : 0;
3395 if (n) {
3396 // color matrix is sent as mat3 matrix followed by vec3
3397 // offset, then packed into a mat4 where the last row is
3398 // the offset and extra values are 0
3399 for (size_t i = 0 ; i < 4; i++) {
3400 for (size_t j = 0; j < 4; j++) {
3401 mColorMatrix[i][j] = data.readFloat();
3402 }
3403 }
3404 } else {
3405 mColorMatrix = mat4();
3406 }
3407 invalidateHwcGeometry();
3408 repaintEverything();
3409 return NO_ERROR;
3410 }
3411 // This is an experimental interface
3412 // Needs to be shifted to proper binder interface when we productize
3413 case 1016: {
3414 n = data.readInt32();
3415 mPrimaryDispSync.setRefreshSkipCount(n);
3416 return NO_ERROR;
3417 }
3418 case 1017: {
3419 n = data.readInt32();
3420 mForceFullDamage = static_cast<bool>(n);
3421 return NO_ERROR;
3422 }
3423 case 1018: { // Modify Choreographer's phase offset
3424 n = data.readInt32();
3425 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3426 return NO_ERROR;
3427 }
3428 case 1019: { // Modify SurfaceFlinger's phase offset
3429 n = data.readInt32();
3430 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3431 return NO_ERROR;
3432 }
3433 case 1020: { // Layer updates interceptor
3434 n = data.readInt32();
3435 if (n) {
3436 ALOGV("Interceptor enabled");
3437 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
3438 }
3439 else{
3440 ALOGV("Interceptor disabled");
3441 mInterceptor.disable();
3442 }
3443 return NO_ERROR;
3444 }
3445 case 1021: { // Disable HWC virtual displays
3446 n = data.readInt32();
3447 mUseHwcVirtualDisplays = !n;
3448 return NO_ERROR;
3449 }
3450 }
3451 }
3452 return err;
3453}
3454
3455void SurfaceFlinger::repaintEverything() {
3456 android_atomic_or(1, &mRepaintEverything);
3457 signalTransaction();
3458}
3459
3460// ---------------------------------------------------------------------------
3461// Capture screen into an IGraphiBufferProducer
3462// ---------------------------------------------------------------------------
3463
3464/* The code below is here to handle b/8734824
3465 *
3466 * We create a IGraphicBufferProducer wrapper that forwards all calls
3467 * from the surfaceflinger thread to the calling binder thread, where they
3468 * are executed. This allows the calling thread in the calling process to be
3469 * reused and not depend on having "enough" binder threads to handle the
3470 * requests.
3471 */
3472class GraphicProducerWrapper : public BBinder, public MessageHandler {
3473 /* Parts of GraphicProducerWrapper are run on two different threads,
3474 * communicating by sending messages via Looper but also by shared member
3475 * data. Coherence maintenance is subtle and in places implicit (ugh).
3476 *
3477 * Don't rely on Looper's sendMessage/handleMessage providing
3478 * release/acquire semantics for any data not actually in the Message.
3479 * Data going from surfaceflinger to binder threads needs to be
3480 * synchronized explicitly.
3481 *
3482 * Barrier open/wait do provide release/acquire semantics. This provides
3483 * implicit synchronization for data coming back from binder to
3484 * surfaceflinger threads.
3485 */
3486
3487 sp<IGraphicBufferProducer> impl;
3488 sp<Looper> looper;
3489 status_t result;
3490 bool exitPending;
3491 bool exitRequested;
3492 Barrier barrier;
3493 uint32_t code;
3494 Parcel const* data;
3495 Parcel* reply;
3496
3497 enum {
3498 MSG_API_CALL,
3499 MSG_EXIT
3500 };
3501
3502 /*
3503 * Called on surfaceflinger thread. This is called by our "fake"
3504 * BpGraphicBufferProducer. We package the data and reply Parcel and
3505 * forward them to the binder thread.
3506 */
3507 virtual status_t transact(uint32_t code,
3508 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
3509 this->code = code;
3510 this->data = &data;
3511 this->reply = reply;
3512 if (exitPending) {
3513 // if we've exited, we run the message synchronously right here.
3514 // note (JH): as far as I can tell from looking at the code, this
3515 // never actually happens. if it does, i'm not sure if it happens
3516 // on the surfaceflinger or binder thread.
3517 handleMessage(Message(MSG_API_CALL));
3518 } else {
3519 barrier.close();
3520 // Prevent stores to this->{code, data, reply} from being
3521 // reordered later than the construction of Message.
3522 atomic_thread_fence(memory_order_release);
3523 looper->sendMessage(this, Message(MSG_API_CALL));
3524 barrier.wait();
3525 }
3526 return result;
3527 }
3528
3529 /*
3530 * here we run on the binder thread. All we've got to do is
3531 * call the real BpGraphicBufferProducer.
3532 */
3533 virtual void handleMessage(const Message& message) {
3534 int what = message.what;
3535 // Prevent reads below from happening before the read from Message
3536 atomic_thread_fence(memory_order_acquire);
3537 if (what == MSG_API_CALL) {
3538 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
3539 barrier.open();
3540 } else if (what == MSG_EXIT) {
3541 exitRequested = true;
3542 }
3543 }
3544
3545public:
3546 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3547 : impl(impl),
3548 looper(new Looper(true)),
3549 result(NO_ERROR),
3550 exitPending(false),
3551 exitRequested(false),
3552 code(0),
3553 data(NULL),
3554 reply(NULL)
3555 {}
3556
3557 // Binder thread
3558 status_t waitForResponse() {
3559 do {
3560 looper->pollOnce(-1);
3561 } while (!exitRequested);
3562 return result;
3563 }
3564
3565 // Client thread
3566 void exit(status_t result) {
3567 this->result = result;
3568 exitPending = true;
3569 // Ensure this->result is visible to the binder thread before it
3570 // handles the message.
3571 atomic_thread_fence(memory_order_release);
3572 looper->sendMessage(this, Message(MSG_EXIT));
3573 }
3574};
3575
3576
3577status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3578 const sp<IGraphicBufferProducer>& producer,
3579 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003580 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003581 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
3582
3583 if (CC_UNLIKELY(display == 0))
3584 return BAD_VALUE;
3585
3586 if (CC_UNLIKELY(producer == 0))
3587 return BAD_VALUE;
3588
3589 // if we have secure windows on this display, never allow the screen capture
3590 // unless the producer interface is local (i.e.: we can take a screenshot for
3591 // ourselves).
3592 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
3593
3594 // Convert to surfaceflinger's internal rotation type.
3595 Transform::orientation_flags rotationFlags;
3596 switch (rotation) {
3597 case ISurfaceComposer::eRotateNone:
3598 rotationFlags = Transform::ROT_0;
3599 break;
3600 case ISurfaceComposer::eRotate90:
3601 rotationFlags = Transform::ROT_90;
3602 break;
3603 case ISurfaceComposer::eRotate180:
3604 rotationFlags = Transform::ROT_180;
3605 break;
3606 case ISurfaceComposer::eRotate270:
3607 rotationFlags = Transform::ROT_270;
3608 break;
3609 default:
3610 rotationFlags = Transform::ROT_0;
3611 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3612 break;
3613 }
3614
3615 class MessageCaptureScreen : public MessageBase {
3616 SurfaceFlinger* flinger;
3617 sp<IBinder> display;
3618 sp<IGraphicBufferProducer> producer;
3619 Rect sourceCrop;
3620 uint32_t reqWidth, reqHeight;
Robert Carrae060832016-11-28 10:51:00 -08003621 int32_t minLayerZ,maxLayerZ;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003622 bool useIdentityTransform;
3623 Transform::orientation_flags rotation;
3624 status_t result;
3625 bool isLocalScreenshot;
3626 public:
3627 MessageCaptureScreen(SurfaceFlinger* flinger,
3628 const sp<IBinder>& display,
3629 const sp<IGraphicBufferProducer>& producer,
3630 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003631 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003632 bool useIdentityTransform,
3633 Transform::orientation_flags rotation,
3634 bool isLocalScreenshot)
3635 : flinger(flinger), display(display), producer(producer),
3636 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
3637 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
3638 useIdentityTransform(useIdentityTransform),
3639 rotation(rotation), result(PERMISSION_DENIED),
3640 isLocalScreenshot(isLocalScreenshot)
3641 {
3642 }
3643 status_t getResult() const {
3644 return result;
3645 }
3646 virtual bool handler() {
3647 Mutex::Autolock _l(flinger->mStateLock);
3648 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
3649 result = flinger->captureScreenImplLocked(hw, producer,
3650 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3651 useIdentityTransform, rotation, isLocalScreenshot);
3652 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
3653 return true;
3654 }
3655 };
3656
3657 // this creates a "fake" BBinder which will serve as a "fake" remote
3658 // binder to receive the marshaled calls and forward them to the
3659 // real remote (a BpGraphicBufferProducer)
3660 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3661
3662 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3663 // which does the marshaling work forwards to our "fake remote" above.
3664 sp<MessageBase> msg = new MessageCaptureScreen(this,
3665 display, IGraphicBufferProducer::asInterface( wrapper ),
3666 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3667 useIdentityTransform, rotationFlags, isLocalScreenshot);
3668
3669 status_t res = postMessageAsync(msg);
3670 if (res == NO_ERROR) {
3671 res = wrapper->waitForResponse();
3672 }
3673 return res;
3674}
3675
3676
3677void SurfaceFlinger::renderScreenImplLocked(
3678 const sp<const DisplayDevice>& hw,
3679 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003680 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003681 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
3682{
3683 ATRACE_CALL();
3684 RenderEngine& engine(getRenderEngine());
3685
3686 // get screen geometry
3687 const int32_t hw_w = hw->getWidth();
3688 const int32_t hw_h = hw->getHeight();
3689 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
3690 static_cast<int32_t>(reqHeight) != hw_h;
3691
3692 // if a default or invalid sourceCrop is passed in, set reasonable values
3693 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3694 !sourceCrop.isValid()) {
3695 sourceCrop.setLeftTop(Point(0, 0));
3696 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3697 }
3698
3699 // ensure that sourceCrop is inside screen
3700 if (sourceCrop.left < 0) {
3701 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3702 }
3703 if (sourceCrop.right > hw_w) {
3704 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
3705 }
3706 if (sourceCrop.top < 0) {
3707 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3708 }
3709 if (sourceCrop.bottom > hw_h) {
3710 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
3711 }
3712
3713 // make sure to clear all GL error flags
3714 engine.checkErrors();
3715
3716 // set-up our viewport
3717 engine.setViewportAndProjection(
3718 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
3719 engine.disableTexturing();
3720
3721 // redraw the screen entirely...
3722 engine.clearWithColor(0, 0, 0, 1);
3723
Robert Carr1f0a16a2016-10-24 16:27:39 -07003724 // We loop through the first level of layers without traversing,
3725 // as we need to interpret min/max layer Z in the top level Z space.
3726 for (const auto& layer : mDrawingState.layersSortedByZ) {
3727 if (layer->getLayerStack() != hw->getLayerStack()) {
3728 continue;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003729 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003730 const Layer::State& state(layer->getDrawingState());
3731 if (state.z < minLayerZ || state.z > maxLayerZ) {
3732 continue;
3733 }
3734 layer->traverseInZOrder([&](Layer* layer) {
3735 if (!layer->isVisible()) {
3736 return;
3737 }
3738 if (filtering) layer->setFiltering(true);
3739 layer->draw(hw, useIdentityTransform);
3740 if (filtering) layer->setFiltering(false);
3741 });
3742 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003743
3744 // compositionComplete is needed for older driver
3745 hw->compositionComplete();
3746 hw->setViewportAndProjection();
3747}
3748
3749
3750status_t SurfaceFlinger::captureScreenImplLocked(
3751 const sp<const DisplayDevice>& hw,
3752 const sp<IGraphicBufferProducer>& producer,
3753 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003754 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003755 bool useIdentityTransform, Transform::orientation_flags rotation,
3756 bool isLocalScreenshot)
3757{
3758 ATRACE_CALL();
3759
3760 // get screen geometry
3761 uint32_t hw_w = hw->getWidth();
3762 uint32_t hw_h = hw->getHeight();
3763
3764 if (rotation & Transform::ROT_90) {
3765 std::swap(hw_w, hw_h);
3766 }
3767
3768 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3769 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3770 reqWidth, reqHeight, hw_w, hw_h);
3771 return BAD_VALUE;
3772 }
3773
3774 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3775 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3776
3777 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07003778 for (const auto& layer : mDrawingState.layersSortedByZ) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003779 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07003780 if ((layer->getLayerStack() != hw->getLayerStack()) ||
3781 (state.z < minLayerZ || state.z > maxLayerZ)) {
3782 continue;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003783 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003784 layer->traverseInZOrder([&](Layer *layer) {
3785 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
3786 layer->isSecure());
3787 });
3788 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003789
3790 if (!isLocalScreenshot && secureLayerIsVisible) {
3791 ALOGW("FB is protected: PERMISSION_DENIED");
3792 return PERMISSION_DENIED;
3793 }
3794
3795 // create a surface (because we're a producer, and we need to
3796 // dequeue/queue a buffer)
3797 sp<Surface> sur = new Surface(producer, false);
3798 ANativeWindow* window = sur.get();
3799
3800 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3801 if (result == NO_ERROR) {
3802 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3803 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
3804
3805 int err = 0;
3806 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
3807 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
3808 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3809 err |= native_window_set_usage(window, usage);
3810
3811 if (err == NO_ERROR) {
3812 ANativeWindowBuffer* buffer;
3813 /* TODO: Once we have the sync framework everywhere this can use
3814 * server-side waits on the fence that dequeueBuffer returns.
3815 */
3816 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3817 if (result == NO_ERROR) {
3818 int syncFd = -1;
3819 // create an EGLImage from the buffer so we can later
3820 // turn it into a texture
3821 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3822 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3823 if (image != EGL_NO_IMAGE_KHR) {
3824 // this binds the given EGLImage as a framebuffer for the
3825 // duration of this scope.
3826 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3827 if (imageBond.getStatus() == NO_ERROR) {
3828 // this will in fact render into our dequeued buffer
3829 // via an FBO, which means we didn't have to create
3830 // an EGLSurface and therefore we're not
3831 // dependent on the context's EGLConfig.
3832 renderScreenImplLocked(
3833 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3834 useIdentityTransform, rotation);
3835
3836 // Attempt to create a sync khr object that can produce a sync point. If that
3837 // isn't available, create a non-dupable sync object in the fallback path and
3838 // wait on it directly.
3839 EGLSyncKHR sync;
3840 if (!DEBUG_SCREENSHOTS) {
3841 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
3842 // native fence fd will not be populated until flush() is done.
3843 getRenderEngine().flush();
3844 } else {
3845 sync = EGL_NO_SYNC_KHR;
3846 }
3847 if (sync != EGL_NO_SYNC_KHR) {
3848 // get the sync fd
3849 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3850 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3851 ALOGW("captureScreen: failed to dup sync khr object");
3852 syncFd = -1;
3853 }
3854 eglDestroySyncKHR(mEGLDisplay, sync);
3855 } else {
3856 // fallback path
3857 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3858 if (sync != EGL_NO_SYNC_KHR) {
3859 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3860 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3861 EGLint eglErr = eglGetError();
3862 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3863 ALOGW("captureScreen: fence wait timed out");
3864 } else {
3865 ALOGW_IF(eglErr != EGL_SUCCESS,
3866 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3867 }
3868 eglDestroySyncKHR(mEGLDisplay, sync);
3869 } else {
3870 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3871 }
3872 }
3873 if (DEBUG_SCREENSHOTS) {
3874 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3875 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3876 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3877 hw, minLayerZ, maxLayerZ);
3878 delete [] pixels;
3879 }
3880
3881 } else {
3882 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3883 result = INVALID_OPERATION;
3884 window->cancelBuffer(window, buffer, syncFd);
3885 buffer = NULL;
3886 }
3887 // destroy our image
3888 eglDestroyImageKHR(mEGLDisplay, image);
3889 } else {
3890 result = BAD_VALUE;
3891 }
3892 if (buffer) {
3893 // queueBuffer takes ownership of syncFd
3894 result = window->queueBuffer(window, buffer, syncFd);
3895 }
3896 }
3897 } else {
3898 result = BAD_VALUE;
3899 }
3900 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3901 }
3902
3903 return result;
3904}
3905
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003906void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08003907 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003908 if (DEBUG_SCREENSHOTS) {
3909 for (size_t y=0 ; y<h ; y++) {
3910 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3911 for (size_t x=0 ; x<w ; x++) {
3912 if (p[x] != 0xFF000000) return;
3913 }
3914 }
3915 ALOGE("*** we just took a black screenshot ***\n"
3916 "requested minz=%d, maxz=%d, layerStack=%d",
3917 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr2047fae2016-11-28 14:09:09 -08003918 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07003919 for (const auto& layer : mDrawingState.layersSortedByZ) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003920 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07003921 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
3922 state.z <= maxLayerZ) {
3923 layer->traverseInZOrder([&](Layer* layer) {
3924 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x",
3925 layer->isVisible() ? '+' : '-',
3926 i, layer->getName().string(), layer->getLayerStack(), state.z,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003927 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003928 i++;
3929 });
3930 }
3931 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003932 }
3933}
3934
3935// ---------------------------------------------------------------------------
3936
Robert Carr2047fae2016-11-28 14:09:09 -08003937void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
3938 layersSortedByZ.traverseInZOrder(consume);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003939}
3940
Robert Carr2047fae2016-11-28 14:09:09 -08003941void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
3942 layersSortedByZ.traverseInReverseZOrder(consume);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003943}
3944
3945}; // namespace android
3946
3947
3948#if defined(__gl_h_)
3949#error "don't include gl/gl.h in this file"
3950#endif
3951
3952#if defined(__gl2_h_)
3953#error "don't include gl2/gl2.h in this file"
3954#endif