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