blob: 2ade006a529d0f1305a8259ef3044078cc863d39 [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
Dan Stoza92cd24e2016-08-09 13:21:03 -07002123status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002124 Mutex::Autolock _l(mStateLock);
Dan Stoza92cd24e2016-08-09 13:21:03 -07002125 sp<Layer> layer = weakLayer.promote();
2126 if (layer == nullptr) {
2127 // The layer has already been removed, carry on
2128 return NO_ERROR;
2129 }
2130
Dan Stoza9e56aa02015-11-02 13:00:03 -08002131 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
2132 if (index >= 0) {
2133 mLayersPendingRemoval.push(layer);
2134 mLayersRemoved = true;
2135 setTransactionFlags(eTransactionNeeded);
2136 return NO_ERROR;
2137 }
2138 return status_t(index);
2139}
2140
2141uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
2142 return android_atomic_release_load(&mTransactionFlags);
2143}
2144
2145uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
2146 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2147}
2148
2149uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
2150 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2151 if ((old & flags)==0) { // wake the server up
2152 signalTransaction();
2153 }
2154 return old;
2155}
2156
2157void SurfaceFlinger::setTransactionState(
2158 const Vector<ComposerState>& state,
2159 const Vector<DisplayState>& displays,
2160 uint32_t flags)
2161{
2162 ATRACE_CALL();
2163 Mutex::Autolock _l(mStateLock);
2164 uint32_t transactionFlags = 0;
2165
2166 if (flags & eAnimation) {
2167 // For window updates that are part of an animation we must wait for
2168 // previous animation "frames" to be handled.
2169 while (mAnimTransactionPending) {
2170 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2171 if (CC_UNLIKELY(err != NO_ERROR)) {
2172 // just in case something goes wrong in SF, return to the
2173 // caller after a few seconds.
2174 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2175 "waiting for previous animation frame");
2176 mAnimTransactionPending = false;
2177 break;
2178 }
2179 }
2180 }
2181
2182 size_t count = displays.size();
2183 for (size_t i=0 ; i<count ; i++) {
2184 const DisplayState& s(displays[i]);
2185 transactionFlags |= setDisplayStateLocked(s);
2186 }
2187
2188 count = state.size();
2189 for (size_t i=0 ; i<count ; i++) {
2190 const ComposerState& s(state[i]);
2191 // Here we need to check that the interface we're given is indeed
2192 // one of our own. A malicious client could give us a NULL
2193 // IInterface, or one of its own or even one of our own but a
2194 // different type. All these situations would cause us to crash.
2195 //
2196 // NOTE: it would be better to use RTTI as we could directly check
2197 // that we have a Client*. however, RTTI is disabled in Android.
2198 if (s.client != NULL) {
2199 sp<IBinder> binder = IInterface::asBinder(s.client);
2200 if (binder != NULL) {
2201 String16 desc(binder->getInterfaceDescriptor());
2202 if (desc == ISurfaceComposerClient::descriptor) {
2203 sp<Client> client( static_cast<Client *>(s.client.get()) );
2204 transactionFlags |= setClientStateLocked(client, s.state);
2205 }
2206 }
2207 }
2208 }
2209
Robert Carr2a7dbb42016-05-24 11:41:28 -07002210 // If a synchronous transaction is explicitly requested without any changes,
2211 // force a transaction anyway. This can be used as a flush mechanism for
2212 // previous async transactions.
2213 if (transactionFlags == 0 && (flags & eSynchronous)) {
2214 transactionFlags = eTransactionNeeded;
2215 }
2216
Dan Stoza9e56aa02015-11-02 13:00:03 -08002217 if (transactionFlags) {
2218 // this triggers the transaction
2219 setTransactionFlags(transactionFlags);
2220
2221 // if this is a synchronous transaction, wait for it to take effect
2222 // before returning.
2223 if (flags & eSynchronous) {
2224 mTransactionPending = true;
2225 }
2226 if (flags & eAnimation) {
2227 mAnimTransactionPending = true;
2228 }
2229 while (mTransactionPending) {
2230 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2231 if (CC_UNLIKELY(err != NO_ERROR)) {
2232 // just in case something goes wrong in SF, return to the
2233 // called after a few seconds.
2234 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2235 mTransactionPending = false;
2236 break;
2237 }
2238 }
2239 }
2240}
2241
2242uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2243{
2244 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2245 if (dpyIdx < 0)
2246 return 0;
2247
2248 uint32_t flags = 0;
2249 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
2250 if (disp.isValid()) {
2251 const uint32_t what = s.what;
2252 if (what & DisplayState::eSurfaceChanged) {
2253 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
2254 disp.surface = s.surface;
2255 flags |= eDisplayTransactionNeeded;
2256 }
2257 }
2258 if (what & DisplayState::eLayerStackChanged) {
2259 if (disp.layerStack != s.layerStack) {
2260 disp.layerStack = s.layerStack;
2261 flags |= eDisplayTransactionNeeded;
2262 }
2263 }
2264 if (what & DisplayState::eDisplayProjectionChanged) {
2265 if (disp.orientation != s.orientation) {
2266 disp.orientation = s.orientation;
2267 flags |= eDisplayTransactionNeeded;
2268 }
2269 if (disp.frame != s.frame) {
2270 disp.frame = s.frame;
2271 flags |= eDisplayTransactionNeeded;
2272 }
2273 if (disp.viewport != s.viewport) {
2274 disp.viewport = s.viewport;
2275 flags |= eDisplayTransactionNeeded;
2276 }
2277 }
2278 if (what & DisplayState::eDisplaySizeChanged) {
2279 if (disp.width != s.width) {
2280 disp.width = s.width;
2281 flags |= eDisplayTransactionNeeded;
2282 }
2283 if (disp.height != s.height) {
2284 disp.height = s.height;
2285 flags |= eDisplayTransactionNeeded;
2286 }
2287 }
2288 }
2289 return flags;
2290}
2291
2292uint32_t SurfaceFlinger::setClientStateLocked(
2293 const sp<Client>& client,
2294 const layer_state_t& s)
2295{
2296 uint32_t flags = 0;
2297 sp<Layer> layer(client->getLayerUser(s.surface));
2298 if (layer != 0) {
2299 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002300 bool geometryAppliesWithResize =
2301 what & layer_state_t::eGeometryAppliesWithResize;
Dan Stoza9e56aa02015-11-02 13:00:03 -08002302 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002303 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002304 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002305 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002306 }
2307 if (what & layer_state_t::eLayerChanged) {
2308 // NOTE: index needs to be calculated before we update the state
2309 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2310 if (layer->setLayer(s.z) && idx >= 0) {
2311 mCurrentState.layersSortedByZ.removeAt(idx);
2312 mCurrentState.layersSortedByZ.add(layer);
2313 // we need traversal (state changed)
2314 // AND transaction (list changed)
2315 flags |= eTransactionNeeded|eTraversalNeeded;
2316 }
2317 }
2318 if (what & layer_state_t::eSizeChanged) {
2319 if (layer->setSize(s.w, s.h)) {
2320 flags |= eTraversalNeeded;
2321 }
2322 }
2323 if (what & layer_state_t::eAlphaChanged) {
2324 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
2325 flags |= eTraversalNeeded;
2326 }
2327 if (what & layer_state_t::eMatrixChanged) {
2328 if (layer->setMatrix(s.matrix))
2329 flags |= eTraversalNeeded;
2330 }
2331 if (what & layer_state_t::eTransparentRegionChanged) {
2332 if (layer->setTransparentRegionHint(s.transparentRegion))
2333 flags |= eTraversalNeeded;
2334 }
2335 if (what & layer_state_t::eFlagsChanged) {
2336 if (layer->setFlags(s.flags, s.mask))
2337 flags |= eTraversalNeeded;
2338 }
2339 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002340 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Dan Stoza9e56aa02015-11-02 13:00:03 -08002341 flags |= eTraversalNeeded;
2342 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002343 if (what & layer_state_t::eFinalCropChanged) {
2344 if (layer->setFinalCrop(s.finalCrop))
2345 flags |= eTraversalNeeded;
2346 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002347 if (what & layer_state_t::eLayerStackChanged) {
2348 // NOTE: index needs to be calculated before we update the state
2349 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2350 if (layer->setLayerStack(s.layerStack) && idx >= 0) {
2351 mCurrentState.layersSortedByZ.removeAt(idx);
2352 mCurrentState.layersSortedByZ.add(layer);
2353 // we need traversal (state changed)
2354 // AND transaction (list changed)
2355 flags |= eTransactionNeeded|eTraversalNeeded;
2356 }
2357 }
2358 if (what & layer_state_t::eDeferTransaction) {
2359 layer->deferTransactionUntil(s.handle, s.frameNumber);
2360 // We don't trigger a traversal here because if no other state is
2361 // changed, we don't want this to cause any more work
2362 }
Robert Carrc3574f72016-03-24 12:19:32 -07002363 if (what & layer_state_t::eOverrideScalingModeChanged) {
2364 layer->setOverrideScalingMode(s.overrideScalingMode);
2365 // We don't trigger a traversal here because if no other state is
2366 // changed, we don't want this to cause any more work
2367 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002368 }
2369 return flags;
2370}
2371
2372status_t SurfaceFlinger::createLayer(
2373 const String8& name,
2374 const sp<Client>& client,
2375 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2376 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
2377{
2378 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
2379 if (int32_t(w|h) < 0) {
2380 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
2381 int(w), int(h));
2382 return BAD_VALUE;
2383 }
2384
2385 status_t result = NO_ERROR;
2386
2387 sp<Layer> layer;
2388
2389 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2390 case ISurfaceComposerClient::eFXSurfaceNormal:
2391 result = createNormalLayer(client,
2392 name, w, h, flags, format,
2393 handle, gbp, &layer);
2394 break;
2395 case ISurfaceComposerClient::eFXSurfaceDim:
2396 result = createDimLayer(client,
2397 name, w, h, flags,
2398 handle, gbp, &layer);
2399 break;
2400 default:
2401 result = BAD_VALUE;
2402 break;
2403 }
2404
2405 if (result != NO_ERROR) {
2406 return result;
2407 }
2408
2409 result = addClientLayer(client, *handle, *gbp, layer);
2410 if (result != NO_ERROR) {
2411 return result;
2412 }
2413
2414 setTransactionFlags(eTransactionNeeded);
2415 return result;
2416}
2417
2418status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2419 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2420 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2421{
2422 // initialize the surfaces
2423 switch (format) {
2424 case PIXEL_FORMAT_TRANSPARENT:
2425 case PIXEL_FORMAT_TRANSLUCENT:
2426 format = PIXEL_FORMAT_RGBA_8888;
2427 break;
2428 case PIXEL_FORMAT_OPAQUE:
2429 format = PIXEL_FORMAT_RGBX_8888;
2430 break;
2431 }
2432
2433 *outLayer = new Layer(this, client, name, w, h, flags);
2434 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2435 if (err == NO_ERROR) {
2436 *handle = (*outLayer)->getHandle();
2437 *gbp = (*outLayer)->getProducer();
2438 }
2439
2440 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2441 return err;
2442}
2443
2444status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2445 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2446 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2447{
2448 *outLayer = new LayerDim(this, client, name, w, h, flags);
2449 *handle = (*outLayer)->getHandle();
2450 *gbp = (*outLayer)->getProducer();
2451 return NO_ERROR;
2452}
2453
2454status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
2455{
2456 // called by the window manager when it wants to remove a Layer
2457 status_t err = NO_ERROR;
2458 sp<Layer> l(client->getLayerUser(handle));
2459 if (l != NULL) {
2460 err = removeLayer(l);
2461 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2462 "error removing layer=%p (%s)", l.get(), strerror(-err));
2463 }
2464 return err;
2465}
2466
2467status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
2468{
2469 // called by ~LayerCleaner() when all references to the IBinder (handle)
2470 // are gone
Dan Stoza92cd24e2016-08-09 13:21:03 -07002471 return removeLayer(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002472}
2473
2474// ---------------------------------------------------------------------------
2475
2476void SurfaceFlinger::onInitializeDisplays() {
2477 // reset screen orientation and use primary layer stack
2478 Vector<ComposerState> state;
2479 Vector<DisplayState> displays;
2480 DisplayState d;
2481 d.what = DisplayState::eDisplayProjectionChanged |
2482 DisplayState::eLayerStackChanged;
2483 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
2484 d.layerStack = 0;
2485 d.orientation = DisplayState::eOrientationDefault;
2486 d.frame.makeInvalid();
2487 d.viewport.makeInvalid();
2488 d.width = 0;
2489 d.height = 0;
2490 displays.add(d);
2491 setTransactionState(state, displays, 0);
2492 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
2493
2494 const nsecs_t period =
2495 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2496 mAnimFrameTracker.setDisplayRefreshPeriod(period);
2497}
2498
2499void SurfaceFlinger::initializeDisplays() {
2500 class MessageScreenInitialized : public MessageBase {
2501 SurfaceFlinger* flinger;
2502 public:
2503 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2504 virtual bool handler() {
2505 flinger->onInitializeDisplays();
2506 return true;
2507 }
2508 };
2509 sp<MessageBase> msg = new MessageScreenInitialized(this);
2510 postMessageAsync(msg); // we may be called from main thread, use async message
2511}
2512
2513void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2514 int mode) {
2515 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2516 this);
2517 int32_t type = hw->getDisplayType();
2518 int currentMode = hw->getPowerMode();
2519
2520 if (mode == currentMode) {
2521 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
2522 return;
2523 }
2524
2525 hw->setPowerMode(mode);
2526 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2527 ALOGW("Trying to set power mode for virtual display");
2528 return;
2529 }
2530
2531 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002532 // Turn on the display
Dan Stoza9e56aa02015-11-02 13:00:03 -08002533 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();
Tim Murrayf9d4e442016-08-02 15:43:59 -07002543
2544 struct sched_param param = {0};
2545 param.sched_priority = 1;
2546 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
2547 ALOGW("Couldn't set SCHED_FIFO on display on");
2548 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002549 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002550 // Turn off the display
2551 struct sched_param param = {0};
2552 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
2553 ALOGW("Couldn't set SCHED_OTHER on display off");
2554 }
2555
Dan Stoza9e56aa02015-11-02 13:00:03 -08002556 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2557 disableHardwareVsync(true); // also cancels any in-progress resync
2558
2559 // FIXME: eventthread only knows about the main display right now
2560 mEventThread->onScreenReleased();
2561 }
2562
2563 getHwComposer().setPowerMode(type, mode);
2564 mVisibleRegionsDirty = true;
2565 // from this point on, SF will stop drawing on this display
2566 } else {
2567 getHwComposer().setPowerMode(type, mode);
2568 }
2569}
2570
2571void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2572 class MessageSetPowerMode: public MessageBase {
2573 SurfaceFlinger& mFlinger;
2574 sp<IBinder> mDisplay;
2575 int mMode;
2576 public:
2577 MessageSetPowerMode(SurfaceFlinger& flinger,
2578 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2579 mDisplay(disp) { mMode = mode; }
2580 virtual bool handler() {
2581 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2582 if (hw == NULL) {
2583 ALOGE("Attempt to set power mode = %d for null display %p",
2584 mMode, mDisplay.get());
2585 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2586 ALOGW("Attempt to set power mode = %d for virtual display",
2587 mMode);
2588 } else {
2589 mFlinger.setPowerModeInternal(hw, mMode);
2590 }
2591 return true;
2592 }
2593 };
2594 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
2595 postMessageSync(msg);
2596}
2597
2598// ---------------------------------------------------------------------------
2599
2600status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2601{
2602 String8 result;
2603
2604 IPCThreadState* ipc = IPCThreadState::self();
2605 const int pid = ipc->getCallingPid();
2606 const int uid = ipc->getCallingUid();
2607 if ((uid != AID_SHELL) &&
2608 !PermissionCache::checkPermission(sDump, pid, uid)) {
2609 result.appendFormat("Permission Denial: "
2610 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
2611 } else {
2612 // Try to get the main lock, but give up after one second
2613 // (this would indicate SF is stuck, but we want to be able to
2614 // print something in dumpsys).
2615 status_t err = mStateLock.timedLock(s2ns(1));
2616 bool locked = (err == NO_ERROR);
2617 if (!locked) {
2618 result.appendFormat(
2619 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2620 "dumping anyways (no locks held)\n", strerror(-err), err);
2621 }
2622
2623 bool dumpAll = true;
2624 size_t index = 0;
2625 size_t numArgs = args.size();
2626 if (numArgs) {
2627 if ((index < numArgs) &&
2628 (args[index] == String16("--list"))) {
2629 index++;
2630 listLayersLocked(args, index, result);
2631 dumpAll = false;
2632 }
2633
2634 if ((index < numArgs) &&
2635 (args[index] == String16("--latency"))) {
2636 index++;
2637 dumpStatsLocked(args, index, result);
2638 dumpAll = false;
2639 }
2640
2641 if ((index < numArgs) &&
2642 (args[index] == String16("--latency-clear"))) {
2643 index++;
2644 clearStatsLocked(args, index, result);
2645 dumpAll = false;
2646 }
2647
2648 if ((index < numArgs) &&
2649 (args[index] == String16("--dispsync"))) {
2650 index++;
2651 mPrimaryDispSync.dump(result);
2652 dumpAll = false;
2653 }
2654
2655 if ((index < numArgs) &&
2656 (args[index] == String16("--static-screen"))) {
2657 index++;
2658 dumpStaticScreenStats(result);
2659 dumpAll = false;
2660 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002661
2662 if ((index < numArgs) &&
2663 (args[index] == String16("--fences"))) {
2664 index++;
2665 mFenceTracker.dump(&result);
2666 dumpAll = false;
2667 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002668 }
2669
2670 if (dumpAll) {
2671 dumpAllLocked(args, index, result);
2672 }
2673
2674 if (locked) {
2675 mStateLock.unlock();
2676 }
2677 }
2678 write(fd, result.string(), result.size());
2679 return NO_ERROR;
2680}
2681
2682void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2683 size_t& /* index */, String8& result) const
2684{
2685 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2686 const size_t count = currentLayers.size();
2687 for (size_t i=0 ; i<count ; i++) {
2688 const sp<Layer>& layer(currentLayers[i]);
2689 result.appendFormat("%s\n", layer->getName().string());
2690 }
2691}
2692
2693void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2694 String8& result) const
2695{
2696 String8 name;
2697 if (index < args.size()) {
2698 name = String8(args[index]);
2699 index++;
2700 }
2701
2702 const nsecs_t period =
2703 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2704 result.appendFormat("%" PRId64 "\n", period);
2705
2706 if (name.isEmpty()) {
2707 mAnimFrameTracker.dumpStats(result);
2708 } else {
2709 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2710 const size_t count = currentLayers.size();
2711 for (size_t i=0 ; i<count ; i++) {
2712 const sp<Layer>& layer(currentLayers[i]);
2713 if (name == layer->getName()) {
2714 layer->dumpFrameStats(result);
2715 }
2716 }
2717 }
2718}
2719
2720void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2721 String8& /* result */)
2722{
2723 String8 name;
2724 if (index < args.size()) {
2725 name = String8(args[index]);
2726 index++;
2727 }
2728
2729 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2730 const size_t count = currentLayers.size();
2731 for (size_t i=0 ; i<count ; i++) {
2732 const sp<Layer>& layer(currentLayers[i]);
2733 if (name.isEmpty() || (name == layer->getName())) {
2734 layer->clearFrameStats();
2735 }
2736 }
2737
2738 mAnimFrameTracker.clearStats();
2739}
2740
2741// This should only be called from the main thread. Otherwise it would need
2742// the lock and should use mCurrentState rather than mDrawingState.
2743void SurfaceFlinger::logFrameStats() {
2744 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2745 const size_t count = drawingLayers.size();
2746 for (size_t i=0 ; i<count ; i++) {
2747 const sp<Layer>& layer(drawingLayers[i]);
2748 layer->logFrameStats();
2749 }
2750
2751 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2752}
2753
2754/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2755{
2756 static const char* config =
2757 " [sf"
2758#ifdef HAS_CONTEXT_PRIORITY
2759 " HAS_CONTEXT_PRIORITY"
2760#endif
2761#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2762 " NEVER_DEFAULT_TO_ASYNC_MODE"
2763#endif
2764#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2765 " TARGET_DISABLE_TRIPLE_BUFFERING"
2766#endif
2767 "]";
2768 result.append(config);
2769}
2770
2771void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2772{
2773 result.appendFormat("Static screen stats:\n");
2774 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2775 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2776 float percent = 100.0f *
2777 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2778 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2779 b + 1, bucketTimeSec, percent);
2780 }
2781 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2782 float percent = 100.0f *
2783 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2784 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2785 NUM_BUCKETS - 1, bucketTimeSec, percent);
2786}
2787
Dan Stozae77c7662016-05-13 11:37:28 -07002788void SurfaceFlinger::recordBufferingStats(const char* layerName,
2789 std::vector<OccupancyTracker::Segment>&& history) {
2790 Mutex::Autolock lock(mBufferingStatsMutex);
2791 auto& stats = mBufferingStats[layerName];
2792 for (const auto& segment : history) {
2793 if (!segment.usedThirdBuffer) {
2794 stats.twoBufferTime += segment.totalTime;
2795 }
2796 if (segment.occupancyAverage < 1.0f) {
2797 stats.doubleBufferedTime += segment.totalTime;
2798 } else if (segment.occupancyAverage < 2.0f) {
2799 stats.tripleBufferedTime += segment.totalTime;
2800 }
2801 ++stats.numSegments;
2802 stats.totalTime += segment.totalTime;
2803 }
2804}
2805
2806void SurfaceFlinger::dumpBufferingStats(String8& result) const {
2807 result.append("Buffering stats:\n");
2808 result.append(" [Layer name] <Active time> <Two buffer> "
2809 "<Double buffered> <Triple buffered>\n");
2810 Mutex::Autolock lock(mBufferingStatsMutex);
2811 typedef std::tuple<std::string, float, float, float> BufferTuple;
2812 std::map<float, BufferTuple, std::greater<float>> sorted;
2813 for (const auto& statsPair : mBufferingStats) {
2814 const char* name = statsPair.first.c_str();
2815 const BufferingStats& stats = statsPair.second;
2816 if (stats.numSegments == 0) {
2817 continue;
2818 }
2819 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
2820 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
2821 stats.totalTime;
2822 float doubleBufferRatio = static_cast<float>(
2823 stats.doubleBufferedTime) / stats.totalTime;
2824 float tripleBufferRatio = static_cast<float>(
2825 stats.tripleBufferedTime) / stats.totalTime;
2826 sorted.insert({activeTime, {name, twoBufferRatio,
2827 doubleBufferRatio, tripleBufferRatio}});
2828 }
2829 for (const auto& sortedPair : sorted) {
2830 float activeTime = sortedPair.first;
2831 const BufferTuple& values = sortedPair.second;
2832 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
2833 std::get<0>(values).c_str(), activeTime,
2834 std::get<1>(values), std::get<2>(values),
2835 std::get<3>(values));
2836 }
2837 result.append("\n");
2838}
2839
Dan Stoza9e56aa02015-11-02 13:00:03 -08002840void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2841 String8& result) const
2842{
2843 bool colorize = false;
2844 if (index < args.size()
2845 && (args[index] == String16("--color"))) {
2846 colorize = true;
2847 index++;
2848 }
2849
2850 Colorizer colorizer(colorize);
2851
2852 // figure out if we're stuck somewhere
2853 const nsecs_t now = systemTime();
2854 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2855 const nsecs_t inTransaction(mDebugInTransaction);
2856 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2857 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2858
2859 /*
2860 * Dump library configuration.
2861 */
2862
2863 colorizer.bold(result);
2864 result.append("Build configuration:");
2865 colorizer.reset(result);
2866 appendSfConfigString(result);
2867 appendUiConfigString(result);
2868 appendGuiConfigString(result);
2869 result.append("\n");
2870
2871 colorizer.bold(result);
2872 result.append("Sync configuration: ");
2873 colorizer.reset(result);
2874 result.append(SyncFeatures::getInstance().toString());
2875 result.append("\n");
2876
2877 colorizer.bold(result);
2878 result.append("DispSync configuration: ");
2879 colorizer.reset(result);
2880 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
2881 "present offset %d ns (refresh %" PRId64 " ns)",
2882 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, PRESENT_TIME_OFFSET_FROM_VSYNC_NS,
2883 mHwc->getRefreshPeriod(HWC_DISPLAY_PRIMARY));
2884 result.append("\n");
2885
2886 // Dump static screen stats
2887 result.append("\n");
2888 dumpStaticScreenStats(result);
2889 result.append("\n");
2890
Dan Stozae77c7662016-05-13 11:37:28 -07002891 dumpBufferingStats(result);
2892
Dan Stoza9e56aa02015-11-02 13:00:03 -08002893 /*
2894 * Dump the visible layer list
2895 */
2896 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2897 const size_t count = currentLayers.size();
2898 colorizer.bold(result);
2899 result.appendFormat("Visible layers (count = %zu)\n", count);
2900 colorizer.reset(result);
2901 for (size_t i=0 ; i<count ; i++) {
2902 const sp<Layer>& layer(currentLayers[i]);
2903 layer->dump(result, colorizer);
2904 }
2905
2906 /*
2907 * Dump Display state
2908 */
2909
2910 colorizer.bold(result);
2911 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
2912 colorizer.reset(result);
2913 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2914 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
2915 hw->dump(result);
2916 }
2917
2918 /*
2919 * Dump SurfaceFlinger global state
2920 */
2921
2922 colorizer.bold(result);
2923 result.append("SurfaceFlinger global state:\n");
2924 colorizer.reset(result);
2925
2926 HWComposer& hwc(getHwComposer());
2927 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2928
2929 colorizer.bold(result);
2930 result.appendFormat("EGL implementation : %s\n",
2931 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2932 colorizer.reset(result);
2933 result.appendFormat("%s\n",
2934 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
2935
2936 mRenderEngine->dump(result);
2937
2938 hw->undefinedRegion.dump(result, "undefinedRegion");
2939 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
2940 hw->getOrientation(), hw->isDisplayOn());
2941 result.appendFormat(
2942 " last eglSwapBuffers() time: %f us\n"
2943 " last transaction time : %f us\n"
2944 " transaction-flags : %08x\n"
2945 " refresh-rate : %f fps\n"
2946 " x-dpi : %f\n"
2947 " y-dpi : %f\n"
2948 " gpu_to_cpu_unsupported : %d\n"
2949 ,
2950 mLastSwapBufferTime/1000.0,
2951 mLastTransactionTime/1000.0,
2952 mTransactionFlags,
2953 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
2954 hwc.getDpiX(HWC_DISPLAY_PRIMARY),
2955 hwc.getDpiY(HWC_DISPLAY_PRIMARY),
2956 !mGpuToCpuSupported);
2957
2958 result.appendFormat(" eglSwapBuffers time: %f us\n",
2959 inSwapBuffersDuration/1000.0);
2960
2961 result.appendFormat(" transaction time: %f us\n",
2962 inTransactionDuration/1000.0);
2963
2964 /*
2965 * VSYNC state
2966 */
2967 mEventThread->dump(result);
2968
2969 /*
2970 * Dump HWComposer state
2971 */
2972 colorizer.bold(result);
2973 result.append("h/w composer state:\n");
2974 colorizer.reset(result);
2975 result.appendFormat(" h/w composer %s and %s\n",
2976 hwc.initCheck()==NO_ERROR ? "present" : "not present",
2977 (mDebugDisableHWC || mDebugRegion || mDaltonize
2978 || mHasColorMatrix) ? "disabled" : "enabled");
2979 hwc.dump(result);
2980
2981 /*
2982 * Dump gralloc state
2983 */
2984 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2985 alloc.dump(result);
2986}
2987
2988const Vector< sp<Layer> >&
2989SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
2990 // Note: mStateLock is held here
2991 wp<IBinder> dpy;
2992 for (size_t i=0 ; i<mDisplays.size() ; i++) {
2993 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2994 dpy = mDisplays.keyAt(i);
2995 break;
2996 }
2997 }
2998 if (dpy == NULL) {
2999 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3000 // Just use the primary display so we have something to return
3001 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3002 }
3003 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
3004}
3005
3006bool SurfaceFlinger::startDdmConnection()
3007{
3008 void* libddmconnection_dso =
3009 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3010 if (!libddmconnection_dso) {
3011 return false;
3012 }
3013 void (*DdmConnection_start)(const char* name);
3014 DdmConnection_start =
3015 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
3016 if (!DdmConnection_start) {
3017 dlclose(libddmconnection_dso);
3018 return false;
3019 }
3020 (*DdmConnection_start)(getServiceName());
3021 return true;
3022}
3023
3024status_t SurfaceFlinger::onTransact(
3025 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3026{
3027 switch (code) {
3028 case CREATE_CONNECTION:
3029 case CREATE_DISPLAY:
3030 case SET_TRANSACTION_STATE:
3031 case BOOT_FINISHED:
3032 case CLEAR_ANIMATION_FRAME_STATS:
3033 case GET_ANIMATION_FRAME_STATS:
3034 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003035 case GET_HDR_CAPABILITIES:
Dan Stoza9e56aa02015-11-02 13:00:03 -08003036 {
3037 // codes that require permission check
3038 IPCThreadState* ipc = IPCThreadState::self();
3039 const int pid = ipc->getCallingPid();
3040 const int uid = ipc->getCallingUid();
3041 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3042 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3043 ALOGE("Permission Denial: "
3044 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3045 return PERMISSION_DENIED;
3046 }
3047 break;
3048 }
3049 case CAPTURE_SCREEN:
3050 {
3051 // codes that require permission check
3052 IPCThreadState* ipc = IPCThreadState::self();
3053 const int pid = ipc->getCallingPid();
3054 const int uid = ipc->getCallingUid();
3055 if ((uid != AID_GRAPHICS) &&
3056 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
3057 ALOGE("Permission Denial: "
3058 "can't read framebuffer pid=%d, uid=%d", pid, uid);
3059 return PERMISSION_DENIED;
3060 }
3061 break;
3062 }
3063 }
3064
3065 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3066 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
3067 CHECK_INTERFACE(ISurfaceComposer, data, reply);
3068 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
3069 IPCThreadState* ipc = IPCThreadState::self();
3070 const int pid = ipc->getCallingPid();
3071 const int uid = ipc->getCallingUid();
3072 ALOGE("Permission Denial: "
3073 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3074 return PERMISSION_DENIED;
3075 }
3076 int n;
3077 switch (code) {
3078 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
3079 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
3080 return NO_ERROR;
3081 case 1002: // SHOW_UPDATES
3082 n = data.readInt32();
3083 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
3084 invalidateHwcGeometry();
3085 repaintEverything();
3086 return NO_ERROR;
3087 case 1004:{ // repaint everything
3088 repaintEverything();
3089 return NO_ERROR;
3090 }
3091 case 1005:{ // force transaction
3092 setTransactionFlags(
3093 eTransactionNeeded|
3094 eDisplayTransactionNeeded|
3095 eTraversalNeeded);
3096 return NO_ERROR;
3097 }
3098 case 1006:{ // send empty update
3099 signalRefresh();
3100 return NO_ERROR;
3101 }
3102 case 1008: // toggle use of hw composer
3103 n = data.readInt32();
3104 mDebugDisableHWC = n ? 1 : 0;
3105 invalidateHwcGeometry();
3106 repaintEverything();
3107 return NO_ERROR;
3108 case 1009: // toggle use of transform hint
3109 n = data.readInt32();
3110 mDebugDisableTransformHint = n ? 1 : 0;
3111 invalidateHwcGeometry();
3112 repaintEverything();
3113 return NO_ERROR;
3114 case 1010: // interrogate.
3115 reply->writeInt32(0);
3116 reply->writeInt32(0);
3117 reply->writeInt32(mDebugRegion);
3118 reply->writeInt32(0);
3119 reply->writeInt32(mDebugDisableHWC);
3120 return NO_ERROR;
3121 case 1013: {
3122 Mutex::Autolock _l(mStateLock);
3123 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3124 reply->writeInt32(hw->getPageFlipCount());
3125 return NO_ERROR;
3126 }
3127 case 1014: {
3128 // daltonize
3129 n = data.readInt32();
3130 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003131 case 1:
3132 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3133 break;
3134 case 2:
3135 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3136 break;
3137 case 3:
3138 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3139 break;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003140 }
3141 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003142 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003143 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003144 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003145 }
3146 mDaltonize = n > 0;
3147 invalidateHwcGeometry();
3148 repaintEverything();
3149 return NO_ERROR;
3150 }
3151 case 1015: {
3152 // apply a color matrix
3153 n = data.readInt32();
3154 mHasColorMatrix = n ? 1 : 0;
3155 if (n) {
3156 // color matrix is sent as mat3 matrix followed by vec3
3157 // offset, then packed into a mat4 where the last row is
3158 // the offset and extra values are 0
3159 for (size_t i = 0 ; i < 4; i++) {
3160 for (size_t j = 0; j < 4; j++) {
3161 mColorMatrix[i][j] = data.readFloat();
3162 }
3163 }
3164 } else {
3165 mColorMatrix = mat4();
3166 }
3167 invalidateHwcGeometry();
3168 repaintEverything();
3169 return NO_ERROR;
3170 }
3171 // This is an experimental interface
3172 // Needs to be shifted to proper binder interface when we productize
3173 case 1016: {
3174 n = data.readInt32();
3175 mPrimaryDispSync.setRefreshSkipCount(n);
3176 return NO_ERROR;
3177 }
3178 case 1017: {
3179 n = data.readInt32();
3180 mForceFullDamage = static_cast<bool>(n);
3181 return NO_ERROR;
3182 }
3183 case 1018: { // Modify Choreographer's phase offset
3184 n = data.readInt32();
3185 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3186 return NO_ERROR;
3187 }
3188 case 1019: { // Modify SurfaceFlinger's phase offset
3189 n = data.readInt32();
3190 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3191 return NO_ERROR;
3192 }
3193 }
3194 }
3195 return err;
3196}
3197
3198void SurfaceFlinger::repaintEverything() {
3199 android_atomic_or(1, &mRepaintEverything);
3200 signalTransaction();
3201}
3202
3203// ---------------------------------------------------------------------------
3204// Capture screen into an IGraphiBufferProducer
3205// ---------------------------------------------------------------------------
3206
3207/* The code below is here to handle b/8734824
3208 *
3209 * We create a IGraphicBufferProducer wrapper that forwards all calls
3210 * from the surfaceflinger thread to the calling binder thread, where they
3211 * are executed. This allows the calling thread in the calling process to be
3212 * reused and not depend on having "enough" binder threads to handle the
3213 * requests.
3214 */
3215class GraphicProducerWrapper : public BBinder, public MessageHandler {
3216 /* Parts of GraphicProducerWrapper are run on two different threads,
3217 * communicating by sending messages via Looper but also by shared member
3218 * data. Coherence maintenance is subtle and in places implicit (ugh).
3219 *
3220 * Don't rely on Looper's sendMessage/handleMessage providing
3221 * release/acquire semantics for any data not actually in the Message.
3222 * Data going from surfaceflinger to binder threads needs to be
3223 * synchronized explicitly.
3224 *
3225 * Barrier open/wait do provide release/acquire semantics. This provides
3226 * implicit synchronization for data coming back from binder to
3227 * surfaceflinger threads.
3228 */
3229
3230 sp<IGraphicBufferProducer> impl;
3231 sp<Looper> looper;
3232 status_t result;
3233 bool exitPending;
3234 bool exitRequested;
3235 Barrier barrier;
3236 uint32_t code;
3237 Parcel const* data;
3238 Parcel* reply;
3239
3240 enum {
3241 MSG_API_CALL,
3242 MSG_EXIT
3243 };
3244
3245 /*
3246 * Called on surfaceflinger thread. This is called by our "fake"
3247 * BpGraphicBufferProducer. We package the data and reply Parcel and
3248 * forward them to the binder thread.
3249 */
3250 virtual status_t transact(uint32_t code,
3251 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
3252 this->code = code;
3253 this->data = &data;
3254 this->reply = reply;
3255 if (exitPending) {
3256 // if we've exited, we run the message synchronously right here.
3257 // note (JH): as far as I can tell from looking at the code, this
3258 // never actually happens. if it does, i'm not sure if it happens
3259 // on the surfaceflinger or binder thread.
3260 handleMessage(Message(MSG_API_CALL));
3261 } else {
3262 barrier.close();
3263 // Prevent stores to this->{code, data, reply} from being
3264 // reordered later than the construction of Message.
3265 atomic_thread_fence(memory_order_release);
3266 looper->sendMessage(this, Message(MSG_API_CALL));
3267 barrier.wait();
3268 }
3269 return result;
3270 }
3271
3272 /*
3273 * here we run on the binder thread. All we've got to do is
3274 * call the real BpGraphicBufferProducer.
3275 */
3276 virtual void handleMessage(const Message& message) {
3277 int what = message.what;
3278 // Prevent reads below from happening before the read from Message
3279 atomic_thread_fence(memory_order_acquire);
3280 if (what == MSG_API_CALL) {
3281 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
3282 barrier.open();
3283 } else if (what == MSG_EXIT) {
3284 exitRequested = true;
3285 }
3286 }
3287
3288public:
3289 GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3290 : impl(impl),
3291 looper(new Looper(true)),
3292 result(NO_ERROR),
3293 exitPending(false),
3294 exitRequested(false),
3295 code(0),
3296 data(NULL),
3297 reply(NULL)
3298 {}
3299
3300 // Binder thread
3301 status_t waitForResponse() {
3302 do {
3303 looper->pollOnce(-1);
3304 } while (!exitRequested);
3305 return result;
3306 }
3307
3308 // Client thread
3309 void exit(status_t result) {
3310 this->result = result;
3311 exitPending = true;
3312 // Ensure this->result is visible to the binder thread before it
3313 // handles the message.
3314 atomic_thread_fence(memory_order_release);
3315 looper->sendMessage(this, Message(MSG_EXIT));
3316 }
3317};
3318
3319
3320status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3321 const sp<IGraphicBufferProducer>& producer,
3322 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3323 uint32_t minLayerZ, uint32_t maxLayerZ,
3324 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
3325
3326 if (CC_UNLIKELY(display == 0))
3327 return BAD_VALUE;
3328
3329 if (CC_UNLIKELY(producer == 0))
3330 return BAD_VALUE;
3331
3332 // if we have secure windows on this display, never allow the screen capture
3333 // unless the producer interface is local (i.e.: we can take a screenshot for
3334 // ourselves).
3335 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
3336
3337 // Convert to surfaceflinger's internal rotation type.
3338 Transform::orientation_flags rotationFlags;
3339 switch (rotation) {
3340 case ISurfaceComposer::eRotateNone:
3341 rotationFlags = Transform::ROT_0;
3342 break;
3343 case ISurfaceComposer::eRotate90:
3344 rotationFlags = Transform::ROT_90;
3345 break;
3346 case ISurfaceComposer::eRotate180:
3347 rotationFlags = Transform::ROT_180;
3348 break;
3349 case ISurfaceComposer::eRotate270:
3350 rotationFlags = Transform::ROT_270;
3351 break;
3352 default:
3353 rotationFlags = Transform::ROT_0;
3354 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3355 break;
3356 }
3357
3358 class MessageCaptureScreen : public MessageBase {
3359 SurfaceFlinger* flinger;
3360 sp<IBinder> display;
3361 sp<IGraphicBufferProducer> producer;
3362 Rect sourceCrop;
3363 uint32_t reqWidth, reqHeight;
3364 uint32_t minLayerZ,maxLayerZ;
3365 bool useIdentityTransform;
3366 Transform::orientation_flags rotation;
3367 status_t result;
3368 bool isLocalScreenshot;
3369 public:
3370 MessageCaptureScreen(SurfaceFlinger* flinger,
3371 const sp<IBinder>& display,
3372 const sp<IGraphicBufferProducer>& producer,
3373 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3374 uint32_t minLayerZ, uint32_t maxLayerZ,
3375 bool useIdentityTransform,
3376 Transform::orientation_flags rotation,
3377 bool isLocalScreenshot)
3378 : flinger(flinger), display(display), producer(producer),
3379 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
3380 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
3381 useIdentityTransform(useIdentityTransform),
3382 rotation(rotation), result(PERMISSION_DENIED),
3383 isLocalScreenshot(isLocalScreenshot)
3384 {
3385 }
3386 status_t getResult() const {
3387 return result;
3388 }
3389 virtual bool handler() {
3390 Mutex::Autolock _l(flinger->mStateLock);
3391 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
3392 result = flinger->captureScreenImplLocked(hw, producer,
3393 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3394 useIdentityTransform, rotation, isLocalScreenshot);
3395 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
3396 return true;
3397 }
3398 };
3399
Dan Stoza9e56aa02015-11-02 13:00:03 -08003400 // this creates a "fake" BBinder which will serve as a "fake" remote
3401 // binder to receive the marshaled calls and forward them to the
3402 // real remote (a BpGraphicBufferProducer)
3403 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3404
3405 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3406 // which does the marshaling work forwards to our "fake remote" above.
3407 sp<MessageBase> msg = new MessageCaptureScreen(this,
3408 display, IGraphicBufferProducer::asInterface( wrapper ),
3409 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3410 useIdentityTransform, rotationFlags, isLocalScreenshot);
3411
3412 status_t res = postMessageAsync(msg);
3413 if (res == NO_ERROR) {
3414 res = wrapper->waitForResponse();
3415 }
3416 return res;
3417}
3418
3419
3420void SurfaceFlinger::renderScreenImplLocked(
3421 const sp<const DisplayDevice>& hw,
3422 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3423 uint32_t minLayerZ, uint32_t maxLayerZ,
3424 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
3425{
3426 ATRACE_CALL();
3427 RenderEngine& engine(getRenderEngine());
3428
3429 // get screen geometry
3430 const int32_t hw_w = hw->getWidth();
3431 const int32_t hw_h = hw->getHeight();
3432 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
3433 static_cast<int32_t>(reqHeight) != hw_h;
3434
3435 // if a default or invalid sourceCrop is passed in, set reasonable values
3436 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3437 !sourceCrop.isValid()) {
3438 sourceCrop.setLeftTop(Point(0, 0));
3439 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3440 }
3441
3442 // ensure that sourceCrop is inside screen
3443 if (sourceCrop.left < 0) {
3444 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3445 }
3446 if (sourceCrop.right > hw_w) {
3447 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
3448 }
3449 if (sourceCrop.top < 0) {
3450 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3451 }
3452 if (sourceCrop.bottom > hw_h) {
3453 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
3454 }
3455
3456 // make sure to clear all GL error flags
3457 engine.checkErrors();
3458
3459 // set-up our viewport
3460 engine.setViewportAndProjection(
3461 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
3462 engine.disableTexturing();
3463
3464 // redraw the screen entirely...
3465 engine.clearWithColor(0, 0, 0, 1);
3466
3467 const LayerVector& layers( mDrawingState.layersSortedByZ );
3468 const size_t count = layers.size();
3469 for (size_t i=0 ; i<count ; ++i) {
3470 const sp<Layer>& layer(layers[i]);
3471 const Layer::State& state(layer->getDrawingState());
3472 if (state.layerStack == hw->getLayerStack()) {
3473 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3474 if (layer->isVisible()) {
3475 if (filtering) layer->setFiltering(true);
3476 layer->draw(hw, useIdentityTransform);
3477 if (filtering) layer->setFiltering(false);
3478 }
3479 }
3480 }
3481 }
3482
3483 // compositionComplete is needed for older driver
3484 hw->compositionComplete();
3485 hw->setViewportAndProjection();
3486}
3487
3488
3489status_t SurfaceFlinger::captureScreenImplLocked(
3490 const sp<const DisplayDevice>& hw,
3491 const sp<IGraphicBufferProducer>& producer,
3492 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3493 uint32_t minLayerZ, uint32_t maxLayerZ,
3494 bool useIdentityTransform, Transform::orientation_flags rotation,
3495 bool isLocalScreenshot)
3496{
3497 ATRACE_CALL();
3498
3499 // get screen geometry
3500 uint32_t hw_w = hw->getWidth();
3501 uint32_t hw_h = hw->getHeight();
3502
3503 if (rotation & Transform::ROT_90) {
3504 std::swap(hw_w, hw_h);
3505 }
3506
3507 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3508 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3509 reqWidth, reqHeight, hw_w, hw_h);
3510 return BAD_VALUE;
3511 }
3512
3513 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3514 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3515
3516 bool secureLayerIsVisible = false;
3517 const LayerVector& layers(mDrawingState.layersSortedByZ);
3518 const size_t count = layers.size();
3519 for (size_t i = 0 ; i < count ; ++i) {
3520 const sp<Layer>& layer(layers[i]);
3521 const Layer::State& state(layer->getDrawingState());
3522 if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ &&
3523 state.z <= maxLayerZ && layer->isVisible() &&
3524 layer->isSecure()) {
3525 secureLayerIsVisible = true;
3526 }
3527 }
3528
3529 if (!isLocalScreenshot && secureLayerIsVisible) {
3530 ALOGW("FB is protected: PERMISSION_DENIED");
3531 return PERMISSION_DENIED;
3532 }
3533
3534 // create a surface (because we're a producer, and we need to
3535 // dequeue/queue a buffer)
3536 sp<Surface> sur = new Surface(producer, false);
3537 ANativeWindow* window = sur.get();
3538
3539 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3540 if (result == NO_ERROR) {
3541 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3542 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
3543
3544 int err = 0;
3545 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
3546 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
3547 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3548 err |= native_window_set_usage(window, usage);
3549
3550 if (err == NO_ERROR) {
3551 ANativeWindowBuffer* buffer;
3552 /* TODO: Once we have the sync framework everywhere this can use
3553 * server-side waits on the fence that dequeueBuffer returns.
3554 */
3555 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3556 if (result == NO_ERROR) {
3557 int syncFd = -1;
3558 // create an EGLImage from the buffer so we can later
3559 // turn it into a texture
3560 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3561 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3562 if (image != EGL_NO_IMAGE_KHR) {
3563 // this binds the given EGLImage as a framebuffer for the
3564 // duration of this scope.
3565 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3566 if (imageBond.getStatus() == NO_ERROR) {
3567 // this will in fact render into our dequeued buffer
3568 // via an FBO, which means we didn't have to create
3569 // an EGLSurface and therefore we're not
3570 // dependent on the context's EGLConfig.
3571 renderScreenImplLocked(
3572 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3573 useIdentityTransform, rotation);
3574
3575 // Attempt to create a sync khr object that can produce a sync point. If that
3576 // isn't available, create a non-dupable sync object in the fallback path and
3577 // wait on it directly.
3578 EGLSyncKHR sync;
3579 if (!DEBUG_SCREENSHOTS) {
3580 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
3581 // native fence fd will not be populated until flush() is done.
3582 getRenderEngine().flush();
3583 } else {
3584 sync = EGL_NO_SYNC_KHR;
3585 }
3586 if (sync != EGL_NO_SYNC_KHR) {
3587 // get the sync fd
3588 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3589 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3590 ALOGW("captureScreen: failed to dup sync khr object");
3591 syncFd = -1;
3592 }
3593 eglDestroySyncKHR(mEGLDisplay, sync);
3594 } else {
3595 // fallback path
3596 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3597 if (sync != EGL_NO_SYNC_KHR) {
3598 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3599 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3600 EGLint eglErr = eglGetError();
3601 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3602 ALOGW("captureScreen: fence wait timed out");
3603 } else {
3604 ALOGW_IF(eglErr != EGL_SUCCESS,
3605 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3606 }
3607 eglDestroySyncKHR(mEGLDisplay, sync);
3608 } else {
3609 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3610 }
3611 }
3612 if (DEBUG_SCREENSHOTS) {
3613 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3614 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3615 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3616 hw, minLayerZ, maxLayerZ);
3617 delete [] pixels;
3618 }
3619
3620 } else {
3621 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3622 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003623 window->cancelBuffer(window, buffer, syncFd);
3624 buffer = NULL;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003625 }
3626 // destroy our image
3627 eglDestroyImageKHR(mEGLDisplay, image);
3628 } else {
3629 result = BAD_VALUE;
3630 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003631 if (buffer) {
3632 // queueBuffer takes ownership of syncFd
3633 result = window->queueBuffer(window, buffer, syncFd);
3634 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003635 }
3636 } else {
3637 result = BAD_VALUE;
3638 }
3639 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3640 }
3641
3642 return result;
3643}
3644
Pablo Ceballosce796e72016-02-04 19:10:51 -08003645bool SurfaceFlinger::getFrameTimestamps(const Layer& layer,
3646 uint64_t frameNumber, FrameTimestamps* outTimestamps) {
3647 return mFenceTracker.getFrameTimestamps(layer, frameNumber, outTimestamps);
3648}
3649
Dan Stoza9e56aa02015-11-02 13:00:03 -08003650void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3651 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
3652 if (DEBUG_SCREENSHOTS) {
3653 for (size_t y=0 ; y<h ; y++) {
3654 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3655 for (size_t x=0 ; x<w ; x++) {
3656 if (p[x] != 0xFF000000) return;
3657 }
3658 }
3659 ALOGE("*** we just took a black screenshot ***\n"
3660 "requested minz=%d, maxz=%d, layerStack=%d",
3661 minLayerZ, maxLayerZ, hw->getLayerStack());
3662 const LayerVector& layers( mDrawingState.layersSortedByZ );
3663 const size_t count = layers.size();
3664 for (size_t i=0 ; i<count ; ++i) {
3665 const sp<Layer>& layer(layers[i]);
3666 const Layer::State& state(layer->getDrawingState());
3667 const bool visible = (state.layerStack == hw->getLayerStack())
3668 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3669 && (layer->isVisible());
3670 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x",
3671 visible ? '+' : '-',
3672 i, layer->getName().string(), state.layerStack, state.z,
3673 layer->isVisible(), state.flags, state.alpha);
3674 }
3675 }
3676}
3677
3678// ---------------------------------------------------------------------------
3679
3680SurfaceFlinger::LayerVector::LayerVector() {
3681}
3682
3683SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
3684 : SortedVector<sp<Layer> >(rhs) {
3685}
3686
3687int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3688 const void* rhs) const
3689{
3690 // sort layers per layer-stack, then by z-order and finally by sequence
3691 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3692 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
3693
3694 uint32_t ls = l->getCurrentState().layerStack;
3695 uint32_t rs = r->getCurrentState().layerStack;
3696 if (ls != rs)
3697 return ls - rs;
3698
3699 uint32_t lz = l->getCurrentState().z;
3700 uint32_t rz = r->getCurrentState().z;
3701 if (lz != rz)
3702 return lz - rz;
3703
3704 return l->sequence - r->sequence;
3705}
3706
3707// ---------------------------------------------------------------------------
3708
3709SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
3710 : type(DisplayDevice::DISPLAY_ID_INVALID),
3711 layerStack(DisplayDevice::NO_LAYER_STACK),
3712 orientation(0),
3713 width(0),
3714 height(0),
3715 isSecure(false) {
3716}
3717
3718SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(
3719 DisplayDevice::DisplayType type, bool isSecure)
3720 : type(type),
3721 layerStack(DisplayDevice::NO_LAYER_STACK),
3722 orientation(0),
3723 width(0),
3724 height(0),
3725 isSecure(isSecure) {
3726 viewport.makeInvalid();
3727 frame.makeInvalid();
3728}
3729
3730// ---------------------------------------------------------------------------
3731
3732}; // namespace android
3733
3734
3735#if defined(__gl_h_)
3736#error "don't include gl/gl.h in this file"
3737#endif
3738
3739#if defined(__gl2_h_)
3740#error "don't include gl2/gl2.h in this file"
3741#endif