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