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