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