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