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