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