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