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