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