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