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