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