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