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