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