blob: bc20bbce4ad3ad4df4e8c91818c35dadd3d98794 [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 }
Robert Carrc3574f72016-03-24 12:19:32 -07002319 if (what & layer_state_t::eOverrideScalingModeChanged) {
2320 layer->setOverrideScalingMode(s.overrideScalingMode);
2321 // We don't trigger a traversal here because if no other state is
2322 // changed, we don't want this to cause any more work
2323 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002324 }
2325 return flags;
2326}
2327
2328status_t SurfaceFlinger::createLayer(
2329 const String8& name,
2330 const sp<Client>& client,
2331 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2332 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
2333{
2334 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
2335 if (int32_t(w|h) < 0) {
2336 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
2337 int(w), int(h));
2338 return BAD_VALUE;
2339 }
2340
2341 status_t result = NO_ERROR;
2342
2343 sp<Layer> layer;
2344
2345 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2346 case ISurfaceComposerClient::eFXSurfaceNormal:
2347 result = createNormalLayer(client,
2348 name, w, h, flags, format,
2349 handle, gbp, &layer);
2350 break;
2351 case ISurfaceComposerClient::eFXSurfaceDim:
2352 result = createDimLayer(client,
2353 name, w, h, flags,
2354 handle, gbp, &layer);
2355 break;
2356 default:
2357 result = BAD_VALUE;
2358 break;
2359 }
2360
2361 if (result != NO_ERROR) {
2362 return result;
2363 }
2364
2365 result = addClientLayer(client, *handle, *gbp, layer);
2366 if (result != NO_ERROR) {
2367 return result;
2368 }
2369
2370 setTransactionFlags(eTransactionNeeded);
2371 return result;
2372}
2373
2374status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2375 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2376 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2377{
2378 // initialize the surfaces
2379 switch (format) {
2380 case PIXEL_FORMAT_TRANSPARENT:
2381 case PIXEL_FORMAT_TRANSLUCENT:
2382 format = PIXEL_FORMAT_RGBA_8888;
2383 break;
2384 case PIXEL_FORMAT_OPAQUE:
2385 format = PIXEL_FORMAT_RGBX_8888;
2386 break;
2387 }
2388
2389 *outLayer = new Layer(this, client, name, w, h, flags);
2390 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2391 if (err == NO_ERROR) {
2392 *handle = (*outLayer)->getHandle();
2393 *gbp = (*outLayer)->getProducer();
2394 }
2395
2396 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2397 return err;
2398}
2399
2400status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2401 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2402 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2403{
2404 *outLayer = new LayerDim(this, client, name, w, h, flags);
2405 *handle = (*outLayer)->getHandle();
2406 *gbp = (*outLayer)->getProducer();
2407 return NO_ERROR;
2408}
2409
2410status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
2411{
2412 // called by the window manager when it wants to remove a Layer
2413 status_t err = NO_ERROR;
2414 sp<Layer> l(client->getLayerUser(handle));
2415 if (l != NULL) {
2416 err = removeLayer(l);
2417 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2418 "error removing layer=%p (%s)", l.get(), strerror(-err));
2419 }
2420 return err;
2421}
2422
2423status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
2424{
2425 // called by ~LayerCleaner() when all references to the IBinder (handle)
2426 // are gone
2427 status_t err = NO_ERROR;
2428 sp<Layer> l(layer.promote());
2429 if (l != NULL) {
2430 err = removeLayer(l);
2431 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2432 "error removing layer=%p (%s)", l.get(), strerror(-err));
2433 }
2434 return err;
2435}
2436
2437// ---------------------------------------------------------------------------
2438
2439void SurfaceFlinger::onInitializeDisplays() {
2440 // reset screen orientation and use primary layer stack
2441 Vector<ComposerState> state;
2442 Vector<DisplayState> displays;
2443 DisplayState d;
2444 d.what = DisplayState::eDisplayProjectionChanged |
2445 DisplayState::eLayerStackChanged;
2446 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
2447 d.layerStack = 0;
2448 d.orientation = DisplayState::eOrientationDefault;
2449 d.frame.makeInvalid();
2450 d.viewport.makeInvalid();
2451 d.width = 0;
2452 d.height = 0;
2453 displays.add(d);
2454 setTransactionState(state, displays, 0);
2455 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
2456
2457 const nsecs_t period =
2458 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2459 mAnimFrameTracker.setDisplayRefreshPeriod(period);
2460}
2461
2462void SurfaceFlinger::initializeDisplays() {
2463 class MessageScreenInitialized : public MessageBase {
2464 SurfaceFlinger* flinger;
2465 public:
2466 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2467 virtual bool handler() {
2468 flinger->onInitializeDisplays();
2469 return true;
2470 }
2471 };
2472 sp<MessageBase> msg = new MessageScreenInitialized(this);
2473 postMessageAsync(msg); // we may be called from main thread, use async message
2474}
2475
2476void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2477 int mode) {
2478 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2479 this);
2480 int32_t type = hw->getDisplayType();
2481 int currentMode = hw->getPowerMode();
2482
2483 if (mode == currentMode) {
2484 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
2485 return;
2486 }
2487
2488 hw->setPowerMode(mode);
2489 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2490 ALOGW("Trying to set power mode for virtual display");
2491 return;
2492 }
2493
2494 if (currentMode == HWC_POWER_MODE_OFF) {
2495 getHwComposer().setPowerMode(type, mode);
2496 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2497 // FIXME: eventthread only knows about the main display right now
2498 mEventThread->onScreenAcquired();
2499 resyncToHardwareVsync(true);
2500 }
2501
2502 mVisibleRegionsDirty = true;
2503 mHasPoweredOff = true;
2504 repaintEverything();
2505 } else if (mode == HWC_POWER_MODE_OFF) {
2506 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2507 disableHardwareVsync(true); // also cancels any in-progress resync
2508
2509 // FIXME: eventthread only knows about the main display right now
2510 mEventThread->onScreenReleased();
2511 }
2512
2513 getHwComposer().setPowerMode(type, mode);
2514 mVisibleRegionsDirty = true;
2515 // from this point on, SF will stop drawing on this display
2516 } else {
2517 getHwComposer().setPowerMode(type, mode);
2518 }
2519}
2520
2521void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2522 class MessageSetPowerMode: public MessageBase {
2523 SurfaceFlinger& mFlinger;
2524 sp<IBinder> mDisplay;
2525 int mMode;
2526 public:
2527 MessageSetPowerMode(SurfaceFlinger& flinger,
2528 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2529 mDisplay(disp) { mMode = mode; }
2530 virtual bool handler() {
2531 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2532 if (hw == NULL) {
2533 ALOGE("Attempt to set power mode = %d for null display %p",
2534 mMode, mDisplay.get());
2535 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2536 ALOGW("Attempt to set power mode = %d for virtual display",
2537 mMode);
2538 } else {
2539 mFlinger.setPowerModeInternal(hw, mMode);
2540 }
2541 return true;
2542 }
2543 };
2544 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
2545 postMessageSync(msg);
2546}
2547
2548// ---------------------------------------------------------------------------
2549
2550status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2551{
2552 String8 result;
2553
2554 IPCThreadState* ipc = IPCThreadState::self();
2555 const int pid = ipc->getCallingPid();
2556 const int uid = ipc->getCallingUid();
2557 if ((uid != AID_SHELL) &&
2558 !PermissionCache::checkPermission(sDump, pid, uid)) {
2559 result.appendFormat("Permission Denial: "
2560 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
2561 } else {
2562 // Try to get the main lock, but give up after one second
2563 // (this would indicate SF is stuck, but we want to be able to
2564 // print something in dumpsys).
2565 status_t err = mStateLock.timedLock(s2ns(1));
2566 bool locked = (err == NO_ERROR);
2567 if (!locked) {
2568 result.appendFormat(
2569 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2570 "dumping anyways (no locks held)\n", strerror(-err), err);
2571 }
2572
2573 bool dumpAll = true;
2574 size_t index = 0;
2575 size_t numArgs = args.size();
2576 if (numArgs) {
2577 if ((index < numArgs) &&
2578 (args[index] == String16("--list"))) {
2579 index++;
2580 listLayersLocked(args, index, result);
2581 dumpAll = false;
2582 }
2583
2584 if ((index < numArgs) &&
2585 (args[index] == String16("--latency"))) {
2586 index++;
2587 dumpStatsLocked(args, index, result);
2588 dumpAll = false;
2589 }
2590
2591 if ((index < numArgs) &&
2592 (args[index] == String16("--latency-clear"))) {
2593 index++;
2594 clearStatsLocked(args, index, result);
2595 dumpAll = false;
2596 }
2597
2598 if ((index < numArgs) &&
2599 (args[index] == String16("--dispsync"))) {
2600 index++;
2601 mPrimaryDispSync.dump(result);
2602 dumpAll = false;
2603 }
2604
2605 if ((index < numArgs) &&
2606 (args[index] == String16("--static-screen"))) {
2607 index++;
2608 dumpStaticScreenStats(result);
2609 dumpAll = false;
2610 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002611
Pablo Ceballos69a1a382016-03-30 15:28:05 -07002612#ifdef ENABLE_FENCE_TRACKING
Pablo Ceballos40845df2016-01-25 17:41:15 -08002613 if ((index < numArgs) &&
2614 (args[index] == String16("--fences"))) {
2615 index++;
2616 mFenceTracker.dump(&result);
2617 dumpAll = false;
2618 }
Pablo Ceballos69a1a382016-03-30 15:28:05 -07002619#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002620 }
2621
2622 if (dumpAll) {
2623 dumpAllLocked(args, index, result);
2624 }
2625
2626 if (locked) {
2627 mStateLock.unlock();
2628 }
2629 }
2630 write(fd, result.string(), result.size());
2631 return NO_ERROR;
2632}
2633
2634void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2635 size_t& /* index */, String8& result) const
2636{
2637 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2638 const size_t count = currentLayers.size();
2639 for (size_t i=0 ; i<count ; i++) {
2640 const sp<Layer>& layer(currentLayers[i]);
2641 result.appendFormat("%s\n", layer->getName().string());
2642 }
2643}
2644
2645void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2646 String8& result) const
2647{
2648 String8 name;
2649 if (index < args.size()) {
2650 name = String8(args[index]);
2651 index++;
2652 }
2653
2654 const nsecs_t period =
2655 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2656 result.appendFormat("%" PRId64 "\n", period);
2657
2658 if (name.isEmpty()) {
2659 mAnimFrameTracker.dumpStats(result);
2660 } else {
2661 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2662 const size_t count = currentLayers.size();
2663 for (size_t i=0 ; i<count ; i++) {
2664 const sp<Layer>& layer(currentLayers[i]);
2665 if (name == layer->getName()) {
2666 layer->dumpFrameStats(result);
2667 }
2668 }
2669 }
2670}
2671
2672void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2673 String8& /* result */)
2674{
2675 String8 name;
2676 if (index < args.size()) {
2677 name = String8(args[index]);
2678 index++;
2679 }
2680
2681 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2682 const size_t count = currentLayers.size();
2683 for (size_t i=0 ; i<count ; i++) {
2684 const sp<Layer>& layer(currentLayers[i]);
2685 if (name.isEmpty() || (name == layer->getName())) {
2686 layer->clearFrameStats();
2687 }
2688 }
2689
2690 mAnimFrameTracker.clearStats();
2691}
2692
2693// This should only be called from the main thread. Otherwise it would need
2694// the lock and should use mCurrentState rather than mDrawingState.
2695void SurfaceFlinger::logFrameStats() {
2696 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2697 const size_t count = drawingLayers.size();
2698 for (size_t i=0 ; i<count ; i++) {
2699 const sp<Layer>& layer(drawingLayers[i]);
2700 layer->logFrameStats();
2701 }
2702
2703 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2704}
2705
2706/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2707{
2708 static const char* config =
2709 " [sf"
2710#ifdef HAS_CONTEXT_PRIORITY
2711 " HAS_CONTEXT_PRIORITY"
2712#endif
2713#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2714 " NEVER_DEFAULT_TO_ASYNC_MODE"
2715#endif
2716#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2717 " TARGET_DISABLE_TRIPLE_BUFFERING"
2718#endif
2719 "]";
2720 result.append(config);
2721}
2722
2723void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2724{
2725 result.appendFormat("Static screen stats:\n");
2726 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2727 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2728 float percent = 100.0f *
2729 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2730 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2731 b + 1, bucketTimeSec, percent);
2732 }
2733 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2734 float percent = 100.0f *
2735 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2736 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2737 NUM_BUCKETS - 1, bucketTimeSec, percent);
2738}
2739
2740void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2741 String8& result) const
2742{
2743 bool colorize = false;
2744 if (index < args.size()
2745 && (args[index] == String16("--color"))) {
2746 colorize = true;
2747 index++;
2748 }
2749
2750 Colorizer colorizer(colorize);
2751
2752 // figure out if we're stuck somewhere
2753 const nsecs_t now = systemTime();
2754 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2755 const nsecs_t inTransaction(mDebugInTransaction);
2756 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2757 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2758
2759 /*
2760 * Dump library configuration.
2761 */
2762
2763 colorizer.bold(result);
2764 result.append("Build configuration:");
2765 colorizer.reset(result);
2766 appendSfConfigString(result);
2767 appendUiConfigString(result);
2768 appendGuiConfigString(result);
2769 result.append("\n");
2770
2771 colorizer.bold(result);
2772 result.append("Sync configuration: ");
2773 colorizer.reset(result);
2774 result.append(SyncFeatures::getInstance().toString());
2775 result.append("\n");
2776
2777 colorizer.bold(result);
2778 result.append("DispSync configuration: ");
2779 colorizer.reset(result);
2780 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
2781 "present offset %d ns (refresh %" PRId64 " ns)",
2782 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, PRESENT_TIME_OFFSET_FROM_VSYNC_NS,
2783 mHwc->getRefreshPeriod(HWC_DISPLAY_PRIMARY));
2784 result.append("\n");
2785
2786 // Dump static screen stats
2787 result.append("\n");
2788 dumpStaticScreenStats(result);
2789 result.append("\n");
2790
2791 /*
2792 * Dump the visible layer list
2793 */
2794 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2795 const size_t count = currentLayers.size();
2796 colorizer.bold(result);
2797 result.appendFormat("Visible layers (count = %zu)\n", count);
2798 colorizer.reset(result);
2799 for (size_t i=0 ; i<count ; i++) {
2800 const sp<Layer>& layer(currentLayers[i]);
2801 layer->dump(result, colorizer);
2802 }
2803
2804 /*
2805 * Dump Display state
2806 */
2807
2808 colorizer.bold(result);
2809 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
2810 colorizer.reset(result);
2811 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2812 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
2813 hw->dump(result);
2814 }
2815
2816 /*
2817 * Dump SurfaceFlinger global state
2818 */
2819
2820 colorizer.bold(result);
2821 result.append("SurfaceFlinger global state:\n");
2822 colorizer.reset(result);
2823
2824 HWComposer& hwc(getHwComposer());
2825 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2826
2827 colorizer.bold(result);
2828 result.appendFormat("EGL implementation : %s\n",
2829 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2830 colorizer.reset(result);
2831 result.appendFormat("%s\n",
2832 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
2833
2834 mRenderEngine->dump(result);
2835
2836 hw->undefinedRegion.dump(result, "undefinedRegion");
2837 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
2838 hw->getOrientation(), hw->isDisplayOn());
2839 result.appendFormat(
2840 " last eglSwapBuffers() time: %f us\n"
2841 " last transaction time : %f us\n"
2842 " transaction-flags : %08x\n"
2843 " refresh-rate : %f fps\n"
2844 " x-dpi : %f\n"
2845 " y-dpi : %f\n"
2846 " gpu_to_cpu_unsupported : %d\n"
2847 ,
2848 mLastSwapBufferTime/1000.0,
2849 mLastTransactionTime/1000.0,
2850 mTransactionFlags,
2851 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
2852 hwc.getDpiX(HWC_DISPLAY_PRIMARY),
2853 hwc.getDpiY(HWC_DISPLAY_PRIMARY),
2854 !mGpuToCpuSupported);
2855
2856 result.appendFormat(" eglSwapBuffers time: %f us\n",
2857 inSwapBuffersDuration/1000.0);
2858
2859 result.appendFormat(" transaction time: %f us\n",
2860 inTransactionDuration/1000.0);
2861
2862 /*
2863 * VSYNC state
2864 */
2865 mEventThread->dump(result);
2866
2867 /*
2868 * Dump HWComposer state
2869 */
2870 colorizer.bold(result);
2871 result.append("h/w composer state:\n");
2872 colorizer.reset(result);
2873 result.appendFormat(" h/w composer %s and %s\n",
2874 hwc.initCheck()==NO_ERROR ? "present" : "not present",
2875 (mDebugDisableHWC || mDebugRegion || mDaltonize
2876 || mHasColorMatrix) ? "disabled" : "enabled");
2877 hwc.dump(result);
2878
2879 /*
2880 * Dump gralloc state
2881 */
2882 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2883 alloc.dump(result);
2884}
2885
2886const Vector< sp<Layer> >&
2887SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
2888 // Note: mStateLock is held here
2889 wp<IBinder> dpy;
2890 for (size_t i=0 ; i<mDisplays.size() ; i++) {
2891 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2892 dpy = mDisplays.keyAt(i);
2893 break;
2894 }
2895 }
2896 if (dpy == NULL) {
2897 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
2898 // Just use the primary display so we have something to return
2899 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
2900 }
2901 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
2902}
2903
2904bool SurfaceFlinger::startDdmConnection()
2905{
2906 void* libddmconnection_dso =
2907 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2908 if (!libddmconnection_dso) {
2909 return false;
2910 }
2911 void (*DdmConnection_start)(const char* name);
2912 DdmConnection_start =
2913 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
2914 if (!DdmConnection_start) {
2915 dlclose(libddmconnection_dso);
2916 return false;
2917 }
2918 (*DdmConnection_start)(getServiceName());
2919 return true;
2920}
2921
2922status_t SurfaceFlinger::onTransact(
2923 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2924{
2925 switch (code) {
2926 case CREATE_CONNECTION:
2927 case CREATE_DISPLAY:
2928 case SET_TRANSACTION_STATE:
2929 case BOOT_FINISHED:
2930 case CLEAR_ANIMATION_FRAME_STATS:
2931 case GET_ANIMATION_FRAME_STATS:
2932 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07002933 case GET_HDR_CAPABILITIES:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002934 {
2935 // codes that require permission check
2936 IPCThreadState* ipc = IPCThreadState::self();
2937 const int pid = ipc->getCallingPid();
2938 const int uid = ipc->getCallingUid();
2939 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
2940 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
2941 ALOGE("Permission Denial: "
2942 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2943 return PERMISSION_DENIED;
2944 }
2945 break;
2946 }
2947 case CAPTURE_SCREEN:
2948 {
2949 // codes that require permission check
2950 IPCThreadState* ipc = IPCThreadState::self();
2951 const int pid = ipc->getCallingPid();
2952 const int uid = ipc->getCallingUid();
2953 if ((uid != AID_GRAPHICS) &&
2954 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
2955 ALOGE("Permission Denial: "
2956 "can't read framebuffer pid=%d, uid=%d", pid, uid);
2957 return PERMISSION_DENIED;
2958 }
2959 break;
2960 }
2961 }
2962
2963 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2964 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
2965 CHECK_INTERFACE(ISurfaceComposer, data, reply);
2966 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
2967 IPCThreadState* ipc = IPCThreadState::self();
2968 const int pid = ipc->getCallingPid();
2969 const int uid = ipc->getCallingUid();
2970 ALOGE("Permission Denial: "
2971 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2972 return PERMISSION_DENIED;
2973 }
2974 int n;
2975 switch (code) {
2976 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
2977 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
2978 return NO_ERROR;
2979 case 1002: // SHOW_UPDATES
2980 n = data.readInt32();
2981 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
2982 invalidateHwcGeometry();
2983 repaintEverything();
2984 return NO_ERROR;
2985 case 1004:{ // repaint everything
2986 repaintEverything();
2987 return NO_ERROR;
2988 }
2989 case 1005:{ // force transaction
2990 setTransactionFlags(
2991 eTransactionNeeded|
2992 eDisplayTransactionNeeded|
2993 eTraversalNeeded);
2994 return NO_ERROR;
2995 }
2996 case 1006:{ // send empty update
2997 signalRefresh();
2998 return NO_ERROR;
2999 }
3000 case 1008: // toggle use of hw composer
3001 n = data.readInt32();
3002 mDebugDisableHWC = n ? 1 : 0;
3003 invalidateHwcGeometry();
3004 repaintEverything();
3005 return NO_ERROR;
3006 case 1009: // toggle use of transform hint
3007 n = data.readInt32();
3008 mDebugDisableTransformHint = n ? 1 : 0;
3009 invalidateHwcGeometry();
3010 repaintEverything();
3011 return NO_ERROR;
3012 case 1010: // interrogate.
3013 reply->writeInt32(0);
3014 reply->writeInt32(0);
3015 reply->writeInt32(mDebugRegion);
3016 reply->writeInt32(0);
3017 reply->writeInt32(mDebugDisableHWC);
3018 return NO_ERROR;
3019 case 1013: {
3020 Mutex::Autolock _l(mStateLock);
3021 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3022 reply->writeInt32(hw->getPageFlipCount());
3023 return NO_ERROR;
3024 }
3025 case 1014: {
3026 // daltonize
3027 n = data.readInt32();
3028 switch (n % 10) {
3029 case 1: mDaltonizer.setType(Daltonizer::protanomaly); break;
3030 case 2: mDaltonizer.setType(Daltonizer::deuteranomaly); break;
3031 case 3: mDaltonizer.setType(Daltonizer::tritanomaly); break;
3032 }
3033 if (n >= 10) {
3034 mDaltonizer.setMode(Daltonizer::correction);
3035 } else {
3036 mDaltonizer.setMode(Daltonizer::simulation);
3037 }
3038 mDaltonize = n > 0;
3039 invalidateHwcGeometry();
3040 repaintEverything();
3041 return NO_ERROR;
3042 }
3043 case 1015: {
3044 // apply a color matrix
3045 n = data.readInt32();
3046 mHasColorMatrix = n ? 1 : 0;
3047 if (n) {
3048 // color matrix is sent as mat3 matrix followed by vec3
3049 // offset, then packed into a mat4 where the last row is
3050 // the offset and extra values are 0
3051 for (size_t i = 0 ; i < 4; i++) {
3052 for (size_t j = 0; j < 4; j++) {
3053 mColorMatrix[i][j] = data.readFloat();
3054 }
3055 }
3056 } else {
3057 mColorMatrix = mat4();
3058 }
3059 invalidateHwcGeometry();
3060 repaintEverything();
3061 return NO_ERROR;
3062 }
3063 // This is an experimental interface
3064 // Needs to be shifted to proper binder interface when we productize
3065 case 1016: {
3066 n = data.readInt32();
3067 mPrimaryDispSync.setRefreshSkipCount(n);
3068 return NO_ERROR;
3069 }
3070 case 1017: {
3071 n = data.readInt32();
3072 mForceFullDamage = static_cast<bool>(n);
3073 return NO_ERROR;
3074 }
3075 case 1018: { // Modify Choreographer's phase offset
3076 n = data.readInt32();
3077 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3078 return NO_ERROR;
3079 }
3080 case 1019: { // Modify SurfaceFlinger's phase offset
3081 n = data.readInt32();
3082 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3083 return NO_ERROR;
3084 }
3085 }
3086 }
3087 return err;
3088}
3089
3090void SurfaceFlinger::repaintEverything() {
3091 android_atomic_or(1, &mRepaintEverything);
3092 signalTransaction();
3093}
3094
3095// ---------------------------------------------------------------------------
3096// Capture screen into an IGraphiBufferProducer
3097// ---------------------------------------------------------------------------
3098
3099/* The code below is here to handle b/8734824
3100 *
3101 * We create a IGraphicBufferProducer wrapper that forwards all calls
3102 * from the surfaceflinger thread to the calling binder thread, where they
3103 * are executed. This allows the calling thread in the calling process to be
3104 * reused and not depend on having "enough" binder threads to handle the
3105 * requests.
3106 */
3107class GraphicProducerWrapper : public BBinder, public MessageHandler {
3108 /* Parts of GraphicProducerWrapper are run on two different threads,
3109 * communicating by sending messages via Looper but also by shared member
3110 * data. Coherence maintenance is subtle and in places implicit (ugh).
3111 *
3112 * Don't rely on Looper's sendMessage/handleMessage providing
3113 * release/acquire semantics for any data not actually in the Message.
3114 * Data going from surfaceflinger to binder threads needs to be
3115 * synchronized explicitly.
3116 *
3117 * Barrier open/wait do provide release/acquire semantics. This provides
3118 * implicit synchronization for data coming back from binder to
3119 * surfaceflinger threads.
3120 */
3121
3122 sp<IGraphicBufferProducer> impl;
3123 sp<Looper> looper;
3124 status_t result;
3125 bool exitPending;
3126 bool exitRequested;
3127 Barrier barrier;
3128 uint32_t code;
3129 Parcel const* data;
3130 Parcel* reply;
3131
3132 enum {
3133 MSG_API_CALL,
3134 MSG_EXIT
3135 };
3136
3137 /*
3138 * Called on surfaceflinger thread. This is called by our "fake"
3139 * BpGraphicBufferProducer. We package the data and reply Parcel and
3140 * forward them to the binder thread.
3141 */
3142 virtual status_t transact(uint32_t code,
3143 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
3144 this->code = code;
3145 this->data = &data;
3146 this->reply = reply;
3147 if (exitPending) {
3148 // if we've exited, we run the message synchronously right here.
3149 // note (JH): as far as I can tell from looking at the code, this
3150 // never actually happens. if it does, i'm not sure if it happens
3151 // on the surfaceflinger or binder thread.
3152 handleMessage(Message(MSG_API_CALL));
3153 } else {
3154 barrier.close();
3155 // Prevent stores to this->{code, data, reply} from being
3156 // reordered later than the construction of Message.
3157 atomic_thread_fence(memory_order_release);
3158 looper->sendMessage(this, Message(MSG_API_CALL));
3159 barrier.wait();
3160 }
3161 return result;
3162 }
3163
3164 /*
3165 * here we run on the binder thread. All we've got to do is
3166 * call the real BpGraphicBufferProducer.
3167 */
3168 virtual void handleMessage(const Message& message) {
3169 int what = message.what;
3170 // Prevent reads below from happening before the read from Message
3171 atomic_thread_fence(memory_order_acquire);
3172 if (what == MSG_API_CALL) {
3173 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
3174 barrier.open();
3175 } else if (what == MSG_EXIT) {
3176 exitRequested = true;
3177 }
3178 }
3179
3180public:
3181 GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3182 : impl(impl),
3183 looper(new Looper(true)),
3184 result(NO_ERROR),
3185 exitPending(false),
3186 exitRequested(false),
3187 code(0),
3188 data(NULL),
3189 reply(NULL)
3190 {}
3191
3192 // Binder thread
3193 status_t waitForResponse() {
3194 do {
3195 looper->pollOnce(-1);
3196 } while (!exitRequested);
3197 return result;
3198 }
3199
3200 // Client thread
3201 void exit(status_t result) {
3202 this->result = result;
3203 exitPending = true;
3204 // Ensure this->result is visible to the binder thread before it
3205 // handles the message.
3206 atomic_thread_fence(memory_order_release);
3207 looper->sendMessage(this, Message(MSG_EXIT));
3208 }
3209};
3210
3211
3212status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3213 const sp<IGraphicBufferProducer>& producer,
3214 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3215 uint32_t minLayerZ, uint32_t maxLayerZ,
3216 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
3217
3218 if (CC_UNLIKELY(display == 0))
3219 return BAD_VALUE;
3220
3221 if (CC_UNLIKELY(producer == 0))
3222 return BAD_VALUE;
3223
3224 // if we have secure windows on this display, never allow the screen capture
3225 // unless the producer interface is local (i.e.: we can take a screenshot for
3226 // ourselves).
3227 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
3228
3229 // Convert to surfaceflinger's internal rotation type.
3230 Transform::orientation_flags rotationFlags;
3231 switch (rotation) {
3232 case ISurfaceComposer::eRotateNone:
3233 rotationFlags = Transform::ROT_0;
3234 break;
3235 case ISurfaceComposer::eRotate90:
3236 rotationFlags = Transform::ROT_90;
3237 break;
3238 case ISurfaceComposer::eRotate180:
3239 rotationFlags = Transform::ROT_180;
3240 break;
3241 case ISurfaceComposer::eRotate270:
3242 rotationFlags = Transform::ROT_270;
3243 break;
3244 default:
3245 rotationFlags = Transform::ROT_0;
3246 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3247 break;
3248 }
3249
3250 class MessageCaptureScreen : public MessageBase {
3251 SurfaceFlinger* flinger;
3252 sp<IBinder> display;
3253 sp<IGraphicBufferProducer> producer;
3254 Rect sourceCrop;
3255 uint32_t reqWidth, reqHeight;
3256 uint32_t minLayerZ,maxLayerZ;
3257 bool useIdentityTransform;
3258 Transform::orientation_flags rotation;
3259 status_t result;
3260 bool isLocalScreenshot;
3261 public:
3262 MessageCaptureScreen(SurfaceFlinger* flinger,
3263 const sp<IBinder>& display,
3264 const sp<IGraphicBufferProducer>& producer,
3265 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3266 uint32_t minLayerZ, uint32_t maxLayerZ,
3267 bool useIdentityTransform,
3268 Transform::orientation_flags rotation,
3269 bool isLocalScreenshot)
3270 : flinger(flinger), display(display), producer(producer),
3271 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
3272 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
3273 useIdentityTransform(useIdentityTransform),
3274 rotation(rotation), result(PERMISSION_DENIED),
3275 isLocalScreenshot(isLocalScreenshot)
3276 {
3277 }
3278 status_t getResult() const {
3279 return result;
3280 }
3281 virtual bool handler() {
3282 Mutex::Autolock _l(flinger->mStateLock);
3283 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
3284 result = flinger->captureScreenImplLocked(hw, producer,
3285 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3286 useIdentityTransform, rotation, isLocalScreenshot);
3287 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
3288 return true;
3289 }
3290 };
3291
3292 // make sure to process transactions before screenshots -- a transaction
3293 // might already be pending but scheduled for VSYNC; this guarantees we
3294 // will handle it before the screenshot. When VSYNC finally arrives
3295 // the scheduled transaction will be a no-op. If no transactions are
3296 // scheduled at this time, this will end-up being a no-op as well.
3297 mEventQueue.invalidateTransactionNow();
3298
3299 // this creates a "fake" BBinder which will serve as a "fake" remote
3300 // binder to receive the marshaled calls and forward them to the
3301 // real remote (a BpGraphicBufferProducer)
3302 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3303
3304 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3305 // which does the marshaling work forwards to our "fake remote" above.
3306 sp<MessageBase> msg = new MessageCaptureScreen(this,
3307 display, IGraphicBufferProducer::asInterface( wrapper ),
3308 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3309 useIdentityTransform, rotationFlags, isLocalScreenshot);
3310
3311 status_t res = postMessageAsync(msg);
3312 if (res == NO_ERROR) {
3313 res = wrapper->waitForResponse();
3314 }
3315 return res;
3316}
3317
3318
3319void SurfaceFlinger::renderScreenImplLocked(
3320 const sp<const DisplayDevice>& hw,
3321 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3322 uint32_t minLayerZ, uint32_t maxLayerZ,
3323 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
3324{
3325 ATRACE_CALL();
3326 RenderEngine& engine(getRenderEngine());
3327
3328 // get screen geometry
3329 const int32_t hw_w = hw->getWidth();
3330 const int32_t hw_h = hw->getHeight();
3331 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
3332 static_cast<int32_t>(reqHeight) != hw_h;
3333
3334 // if a default or invalid sourceCrop is passed in, set reasonable values
3335 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3336 !sourceCrop.isValid()) {
3337 sourceCrop.setLeftTop(Point(0, 0));
3338 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3339 }
3340
3341 // ensure that sourceCrop is inside screen
3342 if (sourceCrop.left < 0) {
3343 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3344 }
3345 if (sourceCrop.right > hw_w) {
3346 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
3347 }
3348 if (sourceCrop.top < 0) {
3349 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3350 }
3351 if (sourceCrop.bottom > hw_h) {
3352 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
3353 }
3354
3355 // make sure to clear all GL error flags
3356 engine.checkErrors();
3357
3358 // set-up our viewport
3359 engine.setViewportAndProjection(
3360 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
3361 engine.disableTexturing();
3362
3363 // redraw the screen entirely...
3364 engine.clearWithColor(0, 0, 0, 1);
3365
3366 const LayerVector& layers( mDrawingState.layersSortedByZ );
3367 const size_t count = layers.size();
3368 for (size_t i=0 ; i<count ; ++i) {
3369 const sp<Layer>& layer(layers[i]);
3370 const Layer::State& state(layer->getDrawingState());
3371 if (state.layerStack == hw->getLayerStack()) {
3372 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3373 if (layer->isVisible()) {
3374 if (filtering) layer->setFiltering(true);
3375 layer->draw(hw, useIdentityTransform);
3376 if (filtering) layer->setFiltering(false);
3377 }
3378 }
3379 }
3380 }
3381
3382 // compositionComplete is needed for older driver
3383 hw->compositionComplete();
3384 hw->setViewportAndProjection();
3385}
3386
3387
3388status_t SurfaceFlinger::captureScreenImplLocked(
3389 const sp<const DisplayDevice>& hw,
3390 const sp<IGraphicBufferProducer>& producer,
3391 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3392 uint32_t minLayerZ, uint32_t maxLayerZ,
3393 bool useIdentityTransform, Transform::orientation_flags rotation,
3394 bool isLocalScreenshot)
3395{
3396 ATRACE_CALL();
3397
3398 // get screen geometry
3399 uint32_t hw_w = hw->getWidth();
3400 uint32_t hw_h = hw->getHeight();
3401
3402 if (rotation & Transform::ROT_90) {
3403 std::swap(hw_w, hw_h);
3404 }
3405
3406 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3407 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3408 reqWidth, reqHeight, hw_w, hw_h);
3409 return BAD_VALUE;
3410 }
3411
3412 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3413 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3414
3415 bool secureLayerIsVisible = false;
3416 const LayerVector& layers(mDrawingState.layersSortedByZ);
3417 const size_t count = layers.size();
3418 for (size_t i = 0 ; i < count ; ++i) {
3419 const sp<Layer>& layer(layers[i]);
3420 const Layer::State& state(layer->getDrawingState());
3421 if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ &&
3422 state.z <= maxLayerZ && layer->isVisible() &&
3423 layer->isSecure()) {
3424 secureLayerIsVisible = true;
3425 }
3426 }
3427
3428 if (!isLocalScreenshot && secureLayerIsVisible) {
3429 ALOGW("FB is protected: PERMISSION_DENIED");
3430 return PERMISSION_DENIED;
3431 }
3432
3433 // create a surface (because we're a producer, and we need to
3434 // dequeue/queue a buffer)
3435 sp<Surface> sur = new Surface(producer, false);
3436 ANativeWindow* window = sur.get();
3437
3438 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3439 if (result == NO_ERROR) {
3440 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3441 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
3442
3443 int err = 0;
3444 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
3445 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
3446 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3447 err |= native_window_set_usage(window, usage);
3448
3449 if (err == NO_ERROR) {
3450 ANativeWindowBuffer* buffer;
3451 /* TODO: Once we have the sync framework everywhere this can use
3452 * server-side waits on the fence that dequeueBuffer returns.
3453 */
3454 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3455 if (result == NO_ERROR) {
3456 int syncFd = -1;
3457 // create an EGLImage from the buffer so we can later
3458 // turn it into a texture
3459 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3460 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3461 if (image != EGL_NO_IMAGE_KHR) {
3462 // this binds the given EGLImage as a framebuffer for the
3463 // duration of this scope.
3464 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3465 if (imageBond.getStatus() == NO_ERROR) {
3466 // this will in fact render into our dequeued buffer
3467 // via an FBO, which means we didn't have to create
3468 // an EGLSurface and therefore we're not
3469 // dependent on the context's EGLConfig.
3470 renderScreenImplLocked(
3471 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3472 useIdentityTransform, rotation);
3473
3474 // Attempt to create a sync khr object that can produce a sync point. If that
3475 // isn't available, create a non-dupable sync object in the fallback path and
3476 // wait on it directly.
3477 EGLSyncKHR sync;
3478 if (!DEBUG_SCREENSHOTS) {
3479 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
3480 // native fence fd will not be populated until flush() is done.
3481 getRenderEngine().flush();
3482 } else {
3483 sync = EGL_NO_SYNC_KHR;
3484 }
3485 if (sync != EGL_NO_SYNC_KHR) {
3486 // get the sync fd
3487 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3488 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3489 ALOGW("captureScreen: failed to dup sync khr object");
3490 syncFd = -1;
3491 }
3492 eglDestroySyncKHR(mEGLDisplay, sync);
3493 } else {
3494 // fallback path
3495 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3496 if (sync != EGL_NO_SYNC_KHR) {
3497 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3498 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3499 EGLint eglErr = eglGetError();
3500 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3501 ALOGW("captureScreen: fence wait timed out");
3502 } else {
3503 ALOGW_IF(eglErr != EGL_SUCCESS,
3504 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3505 }
3506 eglDestroySyncKHR(mEGLDisplay, sync);
3507 } else {
3508 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3509 }
3510 }
3511 if (DEBUG_SCREENSHOTS) {
3512 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3513 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3514 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3515 hw, minLayerZ, maxLayerZ);
3516 delete [] pixels;
3517 }
3518
3519 } else {
3520 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3521 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003522 window->cancelBuffer(window, buffer, syncFd);
3523 buffer = NULL;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003524 }
3525 // destroy our image
3526 eglDestroyImageKHR(mEGLDisplay, image);
3527 } else {
3528 result = BAD_VALUE;
3529 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003530 if (buffer) {
3531 // queueBuffer takes ownership of syncFd
3532 result = window->queueBuffer(window, buffer, syncFd);
3533 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003534 }
3535 } else {
3536 result = BAD_VALUE;
3537 }
3538 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3539 }
3540
3541 return result;
3542}
3543
3544void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3545 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
3546 if (DEBUG_SCREENSHOTS) {
3547 for (size_t y=0 ; y<h ; y++) {
3548 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3549 for (size_t x=0 ; x<w ; x++) {
3550 if (p[x] != 0xFF000000) return;
3551 }
3552 }
3553 ALOGE("*** we just took a black screenshot ***\n"
3554 "requested minz=%d, maxz=%d, layerStack=%d",
3555 minLayerZ, maxLayerZ, hw->getLayerStack());
3556 const LayerVector& layers( mDrawingState.layersSortedByZ );
3557 const size_t count = layers.size();
3558 for (size_t i=0 ; i<count ; ++i) {
3559 const sp<Layer>& layer(layers[i]);
3560 const Layer::State& state(layer->getDrawingState());
3561 const bool visible = (state.layerStack == hw->getLayerStack())
3562 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3563 && (layer->isVisible());
3564 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x",
3565 visible ? '+' : '-',
3566 i, layer->getName().string(), state.layerStack, state.z,
3567 layer->isVisible(), state.flags, state.alpha);
3568 }
3569 }
3570}
3571
3572// ---------------------------------------------------------------------------
3573
3574SurfaceFlinger::LayerVector::LayerVector() {
3575}
3576
3577SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
3578 : SortedVector<sp<Layer> >(rhs) {
3579}
3580
3581int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3582 const void* rhs) const
3583{
3584 // sort layers per layer-stack, then by z-order and finally by sequence
3585 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3586 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
3587
3588 uint32_t ls = l->getCurrentState().layerStack;
3589 uint32_t rs = r->getCurrentState().layerStack;
3590 if (ls != rs)
3591 return ls - rs;
3592
3593 uint32_t lz = l->getCurrentState().z;
3594 uint32_t rz = r->getCurrentState().z;
3595 if (lz != rz)
3596 return lz - rz;
3597
3598 return l->sequence - r->sequence;
3599}
3600
3601// ---------------------------------------------------------------------------
3602
3603SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
3604 : type(DisplayDevice::DISPLAY_ID_INVALID),
3605 layerStack(DisplayDevice::NO_LAYER_STACK),
3606 orientation(0),
3607 width(0),
3608 height(0),
3609 isSecure(false) {
3610}
3611
3612SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(
3613 DisplayDevice::DisplayType type, bool isSecure)
3614 : type(type),
3615 layerStack(DisplayDevice::NO_LAYER_STACK),
3616 orientation(0),
3617 width(0),
3618 height(0),
3619 isSecure(isSecure) {
3620 viewport.makeInvalid();
3621 frame.makeInvalid();
3622}
3623
3624// ---------------------------------------------------------------------------
3625
3626}; // namespace android
3627
3628
3629#if defined(__gl_h_)
3630#error "don't include gl/gl.h in this file"
3631#endif
3632
3633#if defined(__gl2_h_)
3634#error "don't include gl2/gl2.h in this file"
3635#endif