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