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