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