blob: 056d733089746ff024f0670d651484c490237539 [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),
Robert Carr0d480722017-01-10 16:42:54 -0800158 mInterceptor(this),
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000159 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
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800195 property_get("ro.sf.disable_triple_buffer", value, "1");
196 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800197 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);
Robert Carr0d480722017-01-10 16:42:54 -0800631 return authenticateSurfaceTextureLocked(bufferProducer);
632}
633
634bool SurfaceFlinger::authenticateSurfaceTextureLocked(
635 const sp<IGraphicBufferProducer>& bufferProducer) const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000636 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
637 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
638}
639
Brian Anderson069b3652016-07-22 10:32:47 -0700640status_t SurfaceFlinger::getSupportedFrameTimestamps(
Brian Anderson3890c392016-07-25 12:48:08 -0700641 std::vector<FrameEvent>* outSupported) const {
Brian Anderson069b3652016-07-22 10:32:47 -0700642 *outSupported = {
Brian Anderson3890c392016-07-25 12:48:08 -0700643 FrameEvent::REQUESTED_PRESENT,
644 FrameEvent::ACQUIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700645 FrameEvent::LATCH,
Brian Anderson3890c392016-07-25 12:48:08 -0700646 FrameEvent::FIRST_REFRESH_START,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700647 FrameEvent::LAST_REFRESH_START,
Brian Andersonb04c6f02016-10-21 12:57:46 -0700648 FrameEvent::GPU_COMPOSITION_DONE,
Brian Anderson3890c392016-07-25 12:48:08 -0700649 FrameEvent::DISPLAY_RETIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700650 FrameEvent::DEQUEUE_READY,
Brian Anderson3890c392016-07-25 12:48:08 -0700651 FrameEvent::RELEASE,
Brian Anderson069b3652016-07-22 10:32:47 -0700652 };
653 return NO_ERROR;
654}
655
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000656status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
657 Vector<DisplayInfo>* configs) {
658 if ((configs == NULL) || (display.get() == NULL)) {
659 return BAD_VALUE;
660 }
661
662 int32_t type = getDisplayType(display);
663 if (type < 0) return type;
664
665 // TODO: Not sure if display density should handled by SF any longer
666 class Density {
667 static int getDensityFromProperty(char const* propName) {
668 char property[PROPERTY_VALUE_MAX];
669 int density = 0;
670 if (property_get(propName, property, NULL) > 0) {
671 density = atoi(property);
672 }
673 return density;
674 }
675 public:
676 static int getEmuDensity() {
677 return getDensityFromProperty("qemu.sf.lcd_density"); }
678 static int getBuildDensity() {
679 return getDensityFromProperty("ro.sf.lcd_density"); }
680 };
681
682 configs->clear();
683
684 const Vector<HWComposer::DisplayConfig>& hwConfigs =
685 getHwComposer().getConfigs(type);
686 for (size_t c = 0; c < hwConfigs.size(); ++c) {
687 const HWComposer::DisplayConfig& hwConfig = hwConfigs[c];
688 DisplayInfo info = DisplayInfo();
689
690 float xdpi = hwConfig.xdpi;
691 float ydpi = hwConfig.ydpi;
692
693 if (type == DisplayDevice::DISPLAY_PRIMARY) {
694 // The density of the device is provided by a build property
695 float density = Density::getBuildDensity() / 160.0f;
696 if (density == 0) {
697 // the build doesn't provide a density -- this is wrong!
698 // use xdpi instead
699 ALOGE("ro.sf.lcd_density must be defined as a build property");
700 density = xdpi / 160.0f;
701 }
702 if (Density::getEmuDensity()) {
703 // if "qemu.sf.lcd_density" is specified, it overrides everything
704 xdpi = ydpi = density = Density::getEmuDensity();
705 density /= 160.0f;
706 }
707 info.density = density;
708
709 // TODO: this needs to go away (currently needed only by webkit)
710 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
711 info.orientation = hw->getOrientation();
712 } else {
713 // TODO: where should this value come from?
714 static const int TV_DENSITY = 213;
715 info.density = TV_DENSITY / 160.0f;
716 info.orientation = 0;
717 }
718
719 info.w = hwConfig.width;
720 info.h = hwConfig.height;
721 info.xdpi = xdpi;
722 info.ydpi = ydpi;
723 info.fps = float(1e9 / hwConfig.refresh);
724 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
725
726 // This is how far in advance a buffer must be queued for
727 // presentation at a given time. If you want a buffer to appear
728 // on the screen at time N, you must submit the buffer before
729 // (N - presentationDeadline).
730 //
731 // Normally it's one full refresh period (to give SF a chance to
732 // latch the buffer), but this can be reduced by configuring a
733 // DispSync offset. Any additional delays introduced by the hardware
734 // composer or panel must be accounted for here.
735 //
736 // We add an additional 1ms to allow for processing time and
737 // differences between the ideal and actual refresh rate.
738 info.presentationDeadline =
739 hwConfig.refresh - SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
740
741 // All non-virtual displays are currently considered secure.
742 info.secure = true;
743
744 configs->push_back(info);
745 }
746
747 return NO_ERROR;
748}
749
750status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
751 DisplayStatInfo* stats) {
752 if (stats == NULL) {
753 return BAD_VALUE;
754 }
755
756 // FIXME for now we always return stats for the primary display
757 memset(stats, 0, sizeof(*stats));
758 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
759 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
760 return NO_ERROR;
761}
762
763int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
764 sp<DisplayDevice> device(getDisplayDevice(display));
765 if (device != NULL) {
766 return device->getActiveConfig();
767 }
768 return BAD_VALUE;
769}
770
771void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
772 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
773 this);
774 int32_t type = hw->getDisplayType();
775 int currentMode = hw->getActiveConfig();
776
777 if (mode == currentMode) {
778 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
779 return;
780 }
781
782 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
783 ALOGW("Trying to set config for virtual display");
784 return;
785 }
786
787 hw->setActiveConfig(mode);
788 getHwComposer().setActiveConfig(type, mode);
789}
790
791status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
792 class MessageSetActiveConfig: public MessageBase {
793 SurfaceFlinger& mFlinger;
794 sp<IBinder> mDisplay;
795 int mMode;
796 public:
797 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
798 int mode) :
799 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
800 virtual bool handler() {
801 Vector<DisplayInfo> configs;
802 mFlinger.getDisplayConfigs(mDisplay, &configs);
803 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
804 ALOGE("Attempt to set active config = %d for display with %zu configs",
805 mMode, configs.size());
806 }
807 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
808 if (hw == NULL) {
809 ALOGE("Attempt to set active config = %d for null display %p",
810 mMode, mDisplay.get());
811 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
812 ALOGW("Attempt to set active config = %d for virtual display",
813 mMode);
814 } else {
815 mFlinger.setActiveConfigInternal(hw, mMode);
816 }
817 return true;
818 }
819 };
820 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
821 postMessageSync(msg);
822 return NO_ERROR;
823}
824
825status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
826 Vector<android_color_mode_t>* outColorModes) {
827 if (outColorModes == nullptr || display.get() == nullptr) {
828 return BAD_VALUE;
829 }
830
831 int32_t type = getDisplayType(display);
832 if (type < 0) return type;
833
834 std::set<android_color_mode_t> colorModes;
835 for (const HWComposer::DisplayConfig& hwConfig : getHwComposer().getConfigs(type)) {
836 colorModes.insert(hwConfig.colorMode);
837 }
838
839 outColorModes->clear();
840 std::copy(colorModes.cbegin(), colorModes.cend(), std::back_inserter(*outColorModes));
841
842 return NO_ERROR;
843}
844
845android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
846 if (display.get() == nullptr) return static_cast<android_color_mode_t>(BAD_VALUE);
847
848 int32_t type = getDisplayType(display);
849 if (type < 0) return static_cast<android_color_mode_t>(type);
850
851 return getHwComposer().getColorMode(type);
852}
853
854status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
855 android_color_mode_t colorMode) {
856 if (display.get() == nullptr || colorMode < 0) {
857 return BAD_VALUE;
858 }
859
860 int32_t type = getDisplayType(display);
861 if (type < 0) return type;
862 const Vector<HWComposer::DisplayConfig>& hwConfigs = getHwComposer().getConfigs(type);
863 HWComposer::DisplayConfig desiredConfig = hwConfigs[getHwComposer().getCurrentConfig(type)];
864 desiredConfig.colorMode = colorMode;
865 for (size_t c = 0; c < hwConfigs.size(); ++c) {
866 const HWComposer::DisplayConfig config = hwConfigs[c];
867 if (config == desiredConfig) {
868 return setActiveConfig(display, c);
869 }
870 }
871 return BAD_VALUE;
872}
873
874status_t SurfaceFlinger::clearAnimationFrameStats() {
875 Mutex::Autolock _l(mStateLock);
876 mAnimFrameTracker.clearStats();
877 return NO_ERROR;
878}
879
880status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
881 Mutex::Autolock _l(mStateLock);
882 mAnimFrameTracker.getStats(outStats);
883 return NO_ERROR;
884}
885
886status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& /*display*/,
887 HdrCapabilities* outCapabilities) const {
888 // HWC1 does not provide HDR capabilities
889 *outCapabilities = HdrCapabilities();
890 return NO_ERROR;
891}
892
893status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
894 if (enable == mInjectVSyncs) {
895 return NO_ERROR;
896 }
897
898 if (enable) {
899 mInjectVSyncs = enable;
900 ALOGV("VSync Injections enabled");
901 if (mVSyncInjector.get() == nullptr) {
902 mVSyncInjector = new InjectVSyncSource();
903 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
904 }
905 mEventQueue.setEventThread(mInjectorEventThread);
906 } else {
907 mInjectVSyncs = enable;
908 ALOGV("VSync Injections disabled");
909 mEventQueue.setEventThread(mSFEventThread);
910 mVSyncInjector.clear();
911 }
912 return NO_ERROR;
913}
914
915status_t SurfaceFlinger::injectVSync(nsecs_t when) {
916 if (!mInjectVSyncs) {
917 ALOGE("VSync Injections not enabled");
918 return BAD_VALUE;
919 }
920 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
921 ALOGV("Injecting VSync inside SurfaceFlinger");
922 mVSyncInjector->onInjectSyncEvent(when);
923 }
924 return NO_ERROR;
925}
926
927// ----------------------------------------------------------------------------
928
929sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
930 return mEventThread->createEventConnection();
931}
932
933// ----------------------------------------------------------------------------
934
935void SurfaceFlinger::waitForEvent() {
936 mEventQueue.waitMessage();
937}
938
939void SurfaceFlinger::signalTransaction() {
940 mEventQueue.invalidate();
941}
942
943void SurfaceFlinger::signalLayerUpdate() {
944 mEventQueue.invalidate();
945}
946
947void SurfaceFlinger::signalRefresh() {
948 mEventQueue.refresh();
949}
950
951status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
952 nsecs_t reltime, uint32_t /* flags */) {
953 return mEventQueue.postMessage(msg, reltime);
954}
955
956status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
957 nsecs_t reltime, uint32_t /* flags */) {
958 status_t res = mEventQueue.postMessage(msg, reltime);
959 if (res == NO_ERROR) {
960 msg->wait();
961 }
962 return res;
963}
964
965void SurfaceFlinger::run() {
966 do {
967 waitForEvent();
968 } while (true);
969}
970
971void SurfaceFlinger::enableHardwareVsync() {
972 Mutex::Autolock _l(mHWVsyncLock);
973 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
974 mPrimaryDispSync.beginResync();
975 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
976 mEventControlThread->setVsyncEnabled(true);
977 mPrimaryHWVsyncEnabled = true;
978 }
979}
980
981void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
982 Mutex::Autolock _l(mHWVsyncLock);
983
984 if (makeAvailable) {
985 mHWVsyncAvailable = true;
986 } else if (!mHWVsyncAvailable) {
987 // Hardware vsync is not currently available, so abort the resync
988 // attempt for now
989 return;
990 }
991
992 const nsecs_t period =
993 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
994
995 mPrimaryDispSync.reset();
996 mPrimaryDispSync.setPeriod(period);
997
998 if (!mPrimaryHWVsyncEnabled) {
999 mPrimaryDispSync.beginResync();
1000 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1001 mEventControlThread->setVsyncEnabled(true);
1002 mPrimaryHWVsyncEnabled = true;
1003 }
1004}
1005
1006void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
1007 Mutex::Autolock _l(mHWVsyncLock);
1008 if (mPrimaryHWVsyncEnabled) {
1009 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1010 mEventControlThread->setVsyncEnabled(false);
1011 mPrimaryDispSync.endResync();
1012 mPrimaryHWVsyncEnabled = false;
1013 }
1014 if (makeUnavailable) {
1015 mHWVsyncAvailable = false;
1016 }
1017}
1018
1019void SurfaceFlinger::resyncWithRateLimit() {
1020 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1021 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
1022 resyncToHardwareVsync(false);
1023 }
1024}
1025
Steven Thomas3cfac282017-02-06 12:29:30 -08001026void SurfaceFlinger::onVSyncReceived(HWComposer* /*composer*/, int type,
1027 nsecs_t timestamp) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001028 bool needsHwVsync = false;
1029
1030 { // Scope for the lock
1031 Mutex::Autolock _l(mHWVsyncLock);
1032 if (type == 0 && mPrimaryHWVsyncEnabled) {
1033 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
1034 }
1035 }
1036
1037 if (needsHwVsync) {
1038 enableHardwareVsync();
1039 } else {
1040 disableHardwareVsync(false);
1041 }
1042}
1043
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001044void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
1045 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1046 *compositorTiming = mCompositorTiming;
1047}
1048
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001049void SurfaceFlinger::onHotplugReceived(int type, bool connected) {
1050 if (mEventThread == NULL) {
1051 // This is a temporary workaround for b/7145521. A non-null pointer
1052 // does not mean EventThread has finished initializing, so this
1053 // is not a correct fix.
1054 ALOGW("WARNING: EventThread not started, ignoring hotplug");
1055 return;
1056 }
1057
1058 if (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1059 Mutex::Autolock _l(mStateLock);
1060 if (connected) {
1061 createBuiltinDisplayLocked((DisplayDevice::DisplayType)type);
1062 } else {
1063 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1064 mBuiltinDisplays[type].clear();
1065 }
1066 setTransactionFlags(eDisplayTransactionNeeded);
1067
1068 // Defer EventThread notification until SF has updated mDisplays.
1069 }
1070}
1071
Steven Thomas3cfac282017-02-06 12:29:30 -08001072void SurfaceFlinger::onInvalidateReceived(HWComposer* /*composer*/) {
1073 repaintEverything();
1074}
1075
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001076void SurfaceFlinger::eventControl(int disp, int event, int enabled) {
1077 ATRACE_CALL();
1078 getHwComposer().eventControl(disp, event, enabled);
1079}
1080
1081void SurfaceFlinger::onMessageReceived(int32_t what) {
1082 ATRACE_CALL();
1083 switch (what) {
1084 case MessageQueue::INVALIDATE: {
1085 bool refreshNeeded = handleMessageTransaction();
1086 refreshNeeded |= handleMessageInvalidate();
1087 refreshNeeded |= mRepaintEverything;
1088 if (refreshNeeded) {
1089 // Signal a refresh if a transaction modified the window state,
1090 // a new buffer was latched, or if HWC has requested a full
1091 // repaint
1092 signalRefresh();
1093 }
1094 break;
1095 }
1096 case MessageQueue::REFRESH: {
1097 handleMessageRefresh();
1098 break;
1099 }
1100 }
1101}
1102
1103bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001104 uint32_t transactionFlags = peekTransactionFlags();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001105 if (transactionFlags) {
1106 handleTransaction(transactionFlags);
1107 return true;
1108 }
1109 return false;
1110}
1111
1112bool SurfaceFlinger::handleMessageInvalidate() {
1113 ATRACE_CALL();
1114 return handlePageFlip();
1115}
1116
1117void SurfaceFlinger::handleMessageRefresh() {
1118 ATRACE_CALL();
1119
1120 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1121
Brian Andersond6927fb2016-07-23 23:37:30 -07001122 preComposition(refreshStartTime);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001123 rebuildLayerStacks();
1124 setUpHWComposer();
1125 doDebugFlashRegions();
1126 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001127 postComposition(refreshStartTime);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001128}
1129
1130void SurfaceFlinger::doDebugFlashRegions()
1131{
1132 // is debugging enabled
1133 if (CC_LIKELY(!mDebugRegion))
1134 return;
1135
1136 const bool repaintEverything = mRepaintEverything;
1137 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1138 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1139 if (hw->isDisplayOn()) {
1140 // transform the dirty region into this screen's coordinate space
1141 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1142 if (!dirtyRegion.isEmpty()) {
1143 // redraw the whole screen
1144 doComposeSurfaces(hw, Region(hw->bounds()));
1145
1146 // and draw the dirty region
1147 const int32_t height = hw->getHeight();
1148 RenderEngine& engine(getRenderEngine());
1149 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1150
1151 hw->compositionComplete();
1152 hw->swapBuffers(getHwComposer());
1153 }
1154 }
1155 }
1156
1157 postFramebuffer();
1158
1159 if (mDebugRegion > 1) {
1160 usleep(mDebugRegion * 1000);
1161 }
1162
1163 HWComposer& hwc(getHwComposer());
1164 if (hwc.initCheck() == NO_ERROR) {
1165 status_t err = hwc.prepare();
1166 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1167 }
1168}
1169
Brian Andersond6927fb2016-07-23 23:37:30 -07001170void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001171{
1172 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001173 mDrawingState.traverseInZOrder([&](Layer* layer) {
1174 if (layer->onPreComposition(refreshStartTime)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001175 needExtraInvalidate = true;
1176 }
Robert Carr2047fae2016-11-28 14:09:09 -08001177 });
1178
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001179 if (needExtraInvalidate) {
1180 signalLayerUpdate();
1181 }
1182}
1183
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001184void SurfaceFlinger::updateCompositorTiming(
1185 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1186 std::shared_ptr<FenceTime>& presentFenceTime) {
1187 // Update queue of past composite+present times and determine the
1188 // most recently known composite to present latency.
1189 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1190 nsecs_t compositeToPresentLatency = -1;
1191 while (!mCompositePresentTimes.empty()) {
1192 CompositePresentTime& cpt = mCompositePresentTimes.front();
1193 // Cached values should have been updated before calling this method,
1194 // which helps avoid duplicate syscalls.
1195 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1196 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1197 break;
1198 }
1199 compositeToPresentLatency = displayTime - cpt.composite;
1200 mCompositePresentTimes.pop();
1201 }
1202
1203 // Don't let mCompositePresentTimes grow unbounded, just in case.
1204 while (mCompositePresentTimes.size() > 16) {
1205 mCompositePresentTimes.pop();
1206 }
1207
1208 // Integer division and modulo round toward 0 not -inf, so we need to
1209 // treat negative and positive offsets differently.
1210 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs >= 0) ?
1211 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1212 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1213
1214 // Snap the latency to a value that removes scheduling jitter from the
1215 // composition and present times, which often have >1ms of jitter.
1216 // Reducing jitter is important if an app attempts to extrapolate
1217 // something (such as user input) to an accurate diasplay time.
1218 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1219 // with (presentLatency % interval).
1220 nsecs_t snappedCompositeToPresentLatency = -1;
1221 if (compositeToPresentLatency >= 0) {
1222 nsecs_t bias = vsyncInterval / 2;
1223 int64_t extraVsyncs =
1224 (compositeToPresentLatency - idealLatency + bias) /
1225 vsyncInterval;
1226 nsecs_t extraLatency = extraVsyncs * vsyncInterval;
1227 snappedCompositeToPresentLatency = idealLatency + extraLatency;
1228 }
1229
1230 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1231 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1232 mCompositorTiming.interval = vsyncInterval;
1233 if (snappedCompositeToPresentLatency >= 0) {
1234 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
1235 }
1236}
1237
1238void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001239{
Brian Andersond6927fb2016-07-23 23:37:30 -07001240 const HWComposer& hwc = getHwComposer();
1241 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
1242
Brian Anderson3d4039d2016-09-23 16:31:30 -07001243 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1244 if (getHwComposer().hasGlesComposition(hw->getHwcDisplayId())) {
1245 glCompositionDoneFenceTime =
1246 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1247 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1248 } else {
1249 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1250 }
1251 mGlCompositionDoneTimeline.updateSignalTimes();
1252
1253 sp<Fence> displayFence = mHwc->getDisplayFence(HWC_DISPLAY_PRIMARY);
1254 const std::shared_ptr<FenceTime>& presentFenceTime = FenceTime::NO_FENCE;
1255 auto retireFenceTime = std::make_shared<FenceTime>(displayFence);
1256 mDisplayTimeline.push(retireFenceTime);
1257 mDisplayTimeline.updateSignalTimes();
Brian Andersond6927fb2016-07-23 23:37:30 -07001258
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001259 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1260 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1261
1262 // We use the refreshStartTime which might be sampled a little later than
1263 // when we started doing work for this frame, but that should be okay
1264 // since updateCompositorTiming has snapping logic.
1265 updateCompositorTiming(
1266 vsyncPhase, vsyncInterval, refreshStartTime, retireFenceTime);
1267
Robert Carr2047fae2016-11-28 14:09:09 -08001268 mDrawingState.traverseInZOrder([&](Layer* layer) {
1269 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001270 presentFenceTime, retireFenceTime, mCompositorTiming);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001271 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001272 recordBufferingStats(layer->getName().string(),
1273 layer->getOccupancyHistory(false));
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001274 }
Robert Carr2047fae2016-11-28 14:09:09 -08001275 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001276
Brian Anderson3d4039d2016-09-23 16:31:30 -07001277 if (displayFence->isValid()) {
1278 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001279 enableHardwareVsync();
1280 } else {
1281 disableHardwareVsync(false);
1282 }
1283 }
1284
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001285 if (kIgnorePresentFences) {
1286 if (hw->isDisplayOn()) {
1287 enableHardwareVsync();
1288 }
1289 }
1290
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001291 if (mAnimCompositionPending) {
1292 mAnimCompositionPending = false;
1293
Brian Anderson3d4039d2016-09-23 16:31:30 -07001294 if (retireFenceTime->isValid()) {
1295 mAnimFrameTracker.setActualPresentFence(std::move(retireFenceTime));
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001296 } else {
1297 // The HWC doesn't support present fences, so use the refresh
1298 // timestamp instead.
1299 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
1300 mAnimFrameTracker.setActualPresentTime(presentTime);
1301 }
1302 mAnimFrameTracker.advanceFrame();
1303 }
1304
1305 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1306 return;
1307 }
1308
1309 nsecs_t currentTime = systemTime();
1310 if (mHasPoweredOff) {
1311 mHasPoweredOff = false;
1312 } else {
1313 nsecs_t period = mPrimaryDispSync.getPeriod();
1314 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1315 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1316 if (numPeriods < NUM_BUCKETS - 1) {
1317 mFrameBuckets[numPeriods] += elapsedTime;
1318 } else {
1319 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1320 }
1321 mTotalTime += elapsedTime;
1322 }
1323 mLastSwapTime = currentTime;
1324}
1325
1326void SurfaceFlinger::rebuildLayerStacks() {
1327 // rebuild the visible layer list per screen
1328 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1329 ATRACE_CALL();
1330 mVisibleRegionsDirty = false;
1331 invalidateHwcGeometry();
1332
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001333 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1334 Region opaqueRegion;
1335 Region dirtyRegion;
1336 Vector< sp<Layer> > layersSortedByZ;
1337 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1338 const Transform& tr(hw->getTransform());
1339 const Rect bounds(hw->getBounds());
1340 if (hw->isDisplayOn()) {
Robert Carr2047fae2016-11-28 14:09:09 -08001341 computeVisibleRegions(hw->getLayerStack(), dirtyRegion,
1342 opaqueRegion);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001343
Robert Carr2047fae2016-11-28 14:09:09 -08001344 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001345 if (layer->getLayerStack() == hw->getLayerStack()) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001346 Region drawRegion(tr.transform(
1347 layer->visibleNonTransparentRegion));
1348 drawRegion.andSelf(bounds);
1349 if (!drawRegion.isEmpty()) {
1350 layersSortedByZ.add(layer);
1351 }
1352 }
Robert Carr2047fae2016-11-28 14:09:09 -08001353 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001354 }
1355 hw->setVisibleLayersSortedByZ(layersSortedByZ);
1356 hw->undefinedRegion.set(bounds);
1357 hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1358 hw->dirtyRegion.orSelf(dirtyRegion);
1359 }
1360 }
1361}
1362
1363void SurfaceFlinger::setUpHWComposer() {
1364 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1365 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1366 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1367 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1368
1369 // If nothing has changed (!dirty), don't recompose.
1370 // If something changed, but we don't currently have any visible layers,
1371 // and didn't when we last did a composition, then skip it this time.
1372 // The second rule does two things:
1373 // - When all layers are removed from a display, we'll emit one black
1374 // frame, then nothing more until we get new layers.
1375 // - When a display is created with a private layer stack, we won't
1376 // emit any black frames until a layer is added to the layer stack.
1377 bool mustRecompose = dirty && !(empty && wasEmpty);
1378
1379 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1380 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1381 mustRecompose ? "doing" : "skipping",
1382 dirty ? "+" : "-",
1383 empty ? "+" : "-",
1384 wasEmpty ? "+" : "-");
1385
1386 mDisplays[dpy]->beginFrame(mustRecompose);
1387
1388 if (mustRecompose) {
1389 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1390 }
1391 }
1392
1393 HWComposer& hwc(getHwComposer());
1394 if (hwc.initCheck() == NO_ERROR) {
1395 // build the h/w work list
1396 if (CC_UNLIKELY(mHwWorkListDirty)) {
1397 mHwWorkListDirty = false;
1398 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1399 sp<const DisplayDevice> hw(mDisplays[dpy]);
1400 const int32_t id = hw->getHwcDisplayId();
1401 if (id >= 0) {
1402 const Vector< sp<Layer> >& currentLayers(
1403 hw->getVisibleLayersSortedByZ());
1404 const size_t count = currentLayers.size();
1405 if (hwc.createWorkList(id, count) == NO_ERROR) {
1406 HWComposer::LayerListIterator cur = hwc.begin(id);
1407 const HWComposer::LayerListIterator end = hwc.end(id);
1408 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1409 const sp<Layer>& layer(currentLayers[i]);
1410 layer->setGeometry(hw, *cur);
1411 if (mDebugDisableHWC || mDebugRegion || mDaltonize || mHasColorMatrix) {
1412 cur->setSkip(true);
1413 }
1414 }
1415 }
1416 }
1417 }
1418 }
1419
1420 // set the per-frame data
1421 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1422 sp<const DisplayDevice> hw(mDisplays[dpy]);
1423 const int32_t id = hw->getHwcDisplayId();
1424 if (id >= 0) {
1425 const Vector< sp<Layer> >& currentLayers(
1426 hw->getVisibleLayersSortedByZ());
1427 const size_t count = currentLayers.size();
1428 HWComposer::LayerListIterator cur = hwc.begin(id);
1429 const HWComposer::LayerListIterator end = hwc.end(id);
1430 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1431 /*
1432 * update the per-frame h/w composer data for each layer
1433 * and build the transparent region of the FB
1434 */
1435 const sp<Layer>& layer(currentLayers[i]);
1436 layer->setPerFrameData(hw, *cur);
1437 }
1438 }
1439 }
1440
1441 // If possible, attempt to use the cursor overlay on each display.
1442 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1443 sp<const DisplayDevice> hw(mDisplays[dpy]);
1444 const int32_t id = hw->getHwcDisplayId();
1445 if (id >= 0) {
1446 const Vector< sp<Layer> >& currentLayers(
1447 hw->getVisibleLayersSortedByZ());
1448 const size_t count = currentLayers.size();
1449 HWComposer::LayerListIterator cur = hwc.begin(id);
1450 const HWComposer::LayerListIterator end = hwc.end(id);
1451 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1452 const sp<Layer>& layer(currentLayers[i]);
1453 if (layer->isPotentialCursor()) {
1454 cur->setIsCursorLayerHint();
1455 break;
1456 }
1457 }
1458 }
1459 }
1460
1461 status_t err = hwc.prepare();
1462 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1463
1464 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1465 sp<const DisplayDevice> hw(mDisplays[dpy]);
1466 hw->prepareFrame(hwc);
1467 }
1468 }
1469}
1470
1471void SurfaceFlinger::doComposition() {
1472 ATRACE_CALL();
1473 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
1474 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1475 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1476 if (hw->isDisplayOn()) {
1477 // transform the dirty region into this screen's coordinate space
1478 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1479
1480 // repaint the framebuffer (if needed)
1481 doDisplayComposition(hw, dirtyRegion);
1482
1483 hw->dirtyRegion.clear();
1484 hw->flip(hw->swapRegion);
1485 hw->swapRegion.clear();
1486 }
1487 // inform the h/w that we're done compositing
1488 hw->compositionComplete();
1489 }
1490 postFramebuffer();
1491}
1492
1493void SurfaceFlinger::postFramebuffer()
1494{
1495 ATRACE_CALL();
1496
1497 const nsecs_t now = systemTime();
1498 mDebugInSwapBuffers = now;
1499
1500 HWComposer& hwc(getHwComposer());
1501 if (hwc.initCheck() == NO_ERROR) {
1502 if (!hwc.supportsFramebufferTarget()) {
1503 // EGL spec says:
1504 // "surface must be bound to the calling thread's current context,
1505 // for the current rendering API."
1506 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1507 }
1508 hwc.commit();
1509 }
1510
1511 // make the default display current because the VirtualDisplayDevice code cannot
1512 // deal with dequeueBuffer() being called outside of the composition loop; however
1513 // the code below can call glFlush() which is allowed (and does in some case) call
1514 // dequeueBuffer().
1515 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1516
1517 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1518 sp<const DisplayDevice> hw(mDisplays[dpy]);
1519 const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ());
1520 hw->onSwapBuffersCompleted(hwc);
1521 const size_t count = currentLayers.size();
1522 int32_t id = hw->getHwcDisplayId();
1523 if (id >=0 && hwc.initCheck() == NO_ERROR) {
1524 HWComposer::LayerListIterator cur = hwc.begin(id);
1525 const HWComposer::LayerListIterator end = hwc.end(id);
1526 for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
1527 currentLayers[i]->onLayerDisplayed(hw, &*cur);
1528 }
1529 } else {
1530 for (size_t i = 0; i < count; i++) {
1531 currentLayers[i]->onLayerDisplayed(hw, NULL);
1532 }
1533 }
1534 }
1535
1536 mLastSwapBufferTime = systemTime() - now;
1537 mDebugInSwapBuffers = 0;
1538
1539 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1540 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1541 logFrameStats();
1542 }
1543}
1544
1545void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
1546{
1547 ATRACE_CALL();
1548
1549 // here we keep a copy of the drawing state (that is the state that's
1550 // going to be overwritten by handleTransactionLocked()) outside of
1551 // mStateLock so that the side-effects of the State assignment
1552 // don't happen with mStateLock held (which can cause deadlocks).
1553 State drawingState(mDrawingState);
1554
1555 Mutex::Autolock _l(mStateLock);
1556 const nsecs_t now = systemTime();
1557 mDebugInTransaction = now;
1558
1559 // Here we're guaranteed that some transaction flags are set
1560 // so we can call handleTransactionLocked() unconditionally.
1561 // We call getTransactionFlags(), which will also clear the flags,
1562 // with mStateLock held to guarantee that mCurrentState won't change
1563 // until the transaction is committed.
1564
1565 transactionFlags = getTransactionFlags(eTransactionMask);
1566 handleTransactionLocked(transactionFlags);
1567
1568 mLastTransactionTime = systemTime() - now;
1569 mDebugInTransaction = 0;
1570 invalidateHwcGeometry();
1571 // here the transaction has been committed
1572}
1573
1574void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
1575{
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001576 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001577 mCurrentState.traverseInZOrder([](Layer* layer) {
1578 layer->notifyAvailableFrames();
1579 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001580
1581 /*
1582 * Traversal of the children
1583 * (perform the transaction for each of them if needed)
1584 */
1585
1586 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001587 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001588 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001589 if (!trFlags) return;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001590
1591 const uint32_t flags = layer->doTransaction(0);
1592 if (flags & Layer::eVisibleRegion)
1593 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001594 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001595 }
1596
1597 /*
1598 * Perform display own transactions if needed
1599 */
1600
1601 if (transactionFlags & eDisplayTransactionNeeded) {
1602 // here we take advantage of Vector's copy-on-write semantics to
1603 // improve performance by skipping the transaction entirely when
1604 // know that the lists are identical
1605 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1606 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
1607 if (!curr.isIdenticalTo(draw)) {
1608 mVisibleRegionsDirty = true;
1609 const size_t cc = curr.size();
1610 size_t dc = draw.size();
1611
1612 // find the displays that were removed
1613 // (ie: in drawing state but not in current state)
1614 // also handle displays that changed
1615 // (ie: displays that are in both lists)
1616 for (size_t i=0 ; i<dc ; i++) {
1617 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1618 if (j < 0) {
1619 // in drawing state but not in current state
1620 if (!draw[i].isMainDisplay()) {
1621 // Call makeCurrent() on the primary display so we can
1622 // be sure that nothing associated with this display
1623 // is current.
1624 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
1625 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
1626 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1627 if (hw != NULL)
1628 hw->disconnect(getHwComposer());
1629 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
1630 mEventThread->onHotplugReceived(draw[i].type, false);
1631 mDisplays.removeItem(draw.keyAt(i));
1632 } else {
1633 ALOGW("trying to remove the main display");
1634 }
1635 } else {
1636 // this display is in both lists. see if something changed.
1637 const DisplayDeviceState& state(curr[j]);
1638 const wp<IBinder>& display(curr.keyAt(j));
1639 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1640 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
1641 if (state_binder != draw_binder) {
1642 // changing the surface is like destroying and
1643 // recreating the DisplayDevice, so we just remove it
1644 // from the drawing state, so that it get re-added
1645 // below.
1646 sp<DisplayDevice> hw(getDisplayDevice(display));
1647 if (hw != NULL)
1648 hw->disconnect(getHwComposer());
1649 mDisplays.removeItem(display);
1650 mDrawingState.displays.removeItemsAt(i);
1651 dc--; i--;
1652 // at this point we must loop to the next item
1653 continue;
1654 }
1655
1656 const sp<DisplayDevice> disp(getDisplayDevice(display));
1657 if (disp != NULL) {
1658 if (state.layerStack != draw[i].layerStack) {
1659 disp->setLayerStack(state.layerStack);
1660 }
1661 if ((state.orientation != draw[i].orientation)
1662 || (state.viewport != draw[i].viewport)
1663 || (state.frame != draw[i].frame))
1664 {
1665 disp->setProjection(state.orientation,
1666 state.viewport, state.frame);
1667 }
1668 if (state.width != draw[i].width || state.height != draw[i].height) {
1669 disp->setDisplaySize(state.width, state.height);
1670 }
1671 }
1672 }
1673 }
1674
1675 // find displays that were added
1676 // (ie: in current state but not in drawing state)
1677 for (size_t i=0 ; i<cc ; i++) {
1678 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
1679 const DisplayDeviceState& state(curr[i]);
1680
1681 sp<DisplaySurface> dispSurface;
1682 sp<IGraphicBufferProducer> producer;
1683 sp<IGraphicBufferProducer> bqProducer;
1684 sp<IGraphicBufferConsumer> bqConsumer;
1685 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1686 new GraphicBufferAlloc());
1687
1688 int32_t hwcDisplayId = -1;
1689 if (state.isVirtualDisplay()) {
1690 // Virtual displays without a surface are dormant:
1691 // they have external state (layer stack, projection,
1692 // etc.) but no internal state (i.e. a DisplayDevice).
1693 if (state.surface != NULL) {
1694
1695 int width = 0;
1696 int status = state.surface->query(
1697 NATIVE_WINDOW_WIDTH, &width);
1698 ALOGE_IF(status != NO_ERROR,
1699 "Unable to query width (%d)", status);
1700 int height = 0;
1701 status = state.surface->query(
1702 NATIVE_WINDOW_HEIGHT, &height);
1703 ALOGE_IF(status != NO_ERROR,
1704 "Unable to query height (%d)", status);
1705 if (mUseHwcVirtualDisplays &&
1706 (MAX_VIRTUAL_DISPLAY_DIMENSION == 0 ||
1707 (width <= MAX_VIRTUAL_DISPLAY_DIMENSION &&
1708 height <= MAX_VIRTUAL_DISPLAY_DIMENSION))) {
1709 hwcDisplayId = allocateHwcDisplayId(state.type);
1710 }
1711
1712 sp<VirtualDisplaySurface> vds = new VirtualDisplaySurface(
1713 *mHwc, hwcDisplayId, state.surface,
1714 bqProducer, bqConsumer, state.displayName);
1715
1716 dispSurface = vds;
1717 producer = vds;
1718 }
1719 } else {
1720 ALOGE_IF(state.surface!=NULL,
1721 "adding a supported display, but rendering "
1722 "surface is provided (%p), ignoring it",
1723 state.surface.get());
1724 hwcDisplayId = allocateHwcDisplayId(state.type);
1725 // for supported (by hwc) displays we provide our
1726 // own rendering surface
1727 dispSurface = new FramebufferSurface(*mHwc, state.type,
1728 bqConsumer);
1729 producer = bqProducer;
1730 }
1731
1732 const wp<IBinder>& display(curr.keyAt(i));
1733 if (dispSurface != NULL) {
1734 sp<DisplayDevice> hw = new DisplayDevice(this,
1735 state.type, hwcDisplayId,
1736 mHwc->getFormat(hwcDisplayId), state.isSecure,
1737 display, dispSurface, producer,
1738 mRenderEngine->getEGLConfig());
1739 hw->setLayerStack(state.layerStack);
1740 hw->setProjection(state.orientation,
1741 state.viewport, state.frame);
1742 hw->setDisplayName(state.displayName);
1743 mDisplays.add(display, hw);
1744 if (state.isVirtualDisplay()) {
1745 if (hwcDisplayId >= 0) {
1746 mHwc->setVirtualDisplayProperties(hwcDisplayId,
1747 hw->getWidth(), hw->getHeight(),
1748 hw->getFormat());
1749 }
1750 } else {
1751 mEventThread->onHotplugReceived(state.type, true);
1752 }
1753 }
1754 }
1755 }
1756 }
1757 }
1758
1759 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1760 // The transform hint might have changed for some layers
1761 // (either because a display has changed, or because a layer
1762 // as changed).
1763 //
1764 // Walk through all the layers in currentLayers,
1765 // and update their transform hint.
1766 //
1767 // If a layer is visible only on a single display, then that
1768 // display is used to calculate the hint, otherwise we use the
1769 // default display.
1770 //
1771 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1772 // the hint is set before we acquire a buffer from the surface texture.
1773 //
1774 // NOTE: layer transactions have taken place already, so we use their
1775 // drawing state. However, SurfaceFlinger's own transaction has not
1776 // happened yet, so we must use the current state layer list
1777 // (soon to become the drawing state list).
1778 //
1779 sp<const DisplayDevice> disp;
1780 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08001781 bool first = true;
1782 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001783 // NOTE: we rely on the fact that layers are sorted by
1784 // layerStack first (so we don't have to traverse the list
1785 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07001786 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08001787 if (first || currentlayerStack != layerStack) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001788 currentlayerStack = layerStack;
1789 // figure out if this layerstack is mirrored
1790 // (more than one display) if so, pick the default display,
1791 // if not, pick the only display it's on.
1792 disp.clear();
1793 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1794 sp<const DisplayDevice> hw(mDisplays[dpy]);
1795 if (hw->getLayerStack() == currentlayerStack) {
1796 if (disp == NULL) {
1797 disp = hw;
1798 } else {
1799 disp = NULL;
1800 break;
1801 }
1802 }
1803 }
1804 }
1805 if (disp == NULL) {
1806 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1807 // redraw after transform hint changes. See bug 8508397.
1808
1809 // could be null when this layer is using a layerStack
1810 // that is not visible on any display. Also can occur at
1811 // screen off/on times.
1812 disp = getDefaultDisplayDevice();
1813 }
1814 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08001815
1816 first = false;
1817 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001818 }
1819
1820
1821 /*
1822 * Perform our own transaction if needed
1823 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07001824
1825 if (mLayersAdded) {
1826 mLayersAdded = false;
1827 // Layers have been added.
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001828 mVisibleRegionsDirty = true;
1829 }
1830
1831 // some layers might have been removed, so
1832 // we need to update the regions they're exposing.
1833 if (mLayersRemoved) {
1834 mLayersRemoved = false;
1835 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001836 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001837 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001838 // this layer is not visible anymore
1839 // TODO: we could traverse the tree from front to back and
1840 // compute the actual visible region
1841 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07001842 Region visibleReg;
1843 visibleReg.set(layer->computeScreenBounds());
1844 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001845 }
Robert Carr2047fae2016-11-28 14:09:09 -08001846 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001847 }
1848
1849 commitTransaction();
1850
1851 updateCursorAsync();
1852}
1853
1854void SurfaceFlinger::updateCursorAsync()
1855{
1856 HWComposer& hwc(getHwComposer());
1857 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1858 sp<const DisplayDevice> hw(mDisplays[dpy]);
1859 const int32_t id = hw->getHwcDisplayId();
1860 if (id < 0) {
1861 continue;
1862 }
1863 const Vector< sp<Layer> >& currentLayers(
1864 hw->getVisibleLayersSortedByZ());
1865 const size_t count = currentLayers.size();
1866 HWComposer::LayerListIterator cur = hwc.begin(id);
1867 const HWComposer::LayerListIterator end = hwc.end(id);
1868 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1869 if (cur->getCompositionType() != HWC_CURSOR_OVERLAY) {
1870 continue;
1871 }
1872 const sp<Layer>& layer(currentLayers[i]);
1873 Rect cursorPos = layer->getPosition(hw);
1874 hwc.setCursorPositionAsync(id, cursorPos);
1875 break;
1876 }
1877 }
1878}
1879
1880void SurfaceFlinger::commitTransaction()
1881{
1882 if (!mLayersPendingRemoval.isEmpty()) {
1883 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07001884 for (const auto& l : mLayersPendingRemoval) {
1885 recordBufferingStats(l->getName().string(),
1886 l->getOccupancyHistory(true));
1887 l->onRemoved();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001888 }
1889 mLayersPendingRemoval.clear();
1890 }
1891
1892 // If this transaction is part of a window animation then the next frame
1893 // we composite should be considered an animation as well.
1894 mAnimCompositionPending = mAnimTransactionPending;
1895
1896 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001897 mDrawingState.traverseInZOrder([](Layer* layer) {
1898 layer->commitChildList();
1899 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001900 mTransactionPending = false;
1901 mAnimTransactionPending = false;
1902 mTransactionCV.broadcast();
1903}
1904
Robert Carr2047fae2016-11-28 14:09:09 -08001905void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001906 Region& outDirtyRegion, Region& outOpaqueRegion)
1907{
1908 ATRACE_CALL();
1909
1910 Region aboveOpaqueLayers;
1911 Region aboveCoveredLayers;
1912 Region dirty;
1913
1914 outDirtyRegion.clear();
1915
Robert Carr2047fae2016-11-28 14:09:09 -08001916 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001917 // start with the whole surface at its current location
1918 const Layer::State& s(layer->getDrawingState());
1919
1920 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07001921 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08001922 return;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001923
1924 /*
1925 * opaqueRegion: area of a surface that is fully opaque.
1926 */
1927 Region opaqueRegion;
1928
1929 /*
1930 * visibleRegion: area of a surface that is visible on screen
1931 * and not fully transparent. This is essentially the layer's
1932 * footprint minus the opaque regions above it.
1933 * Areas covered by a translucent surface are considered visible.
1934 */
1935 Region visibleRegion;
1936
1937 /*
1938 * coveredRegion: area of a surface that is covered by all
1939 * visible regions above it (which includes the translucent areas).
1940 */
1941 Region coveredRegion;
1942
1943 /*
1944 * transparentRegion: area of a surface that is hinted to be completely
1945 * transparent. This is only used to tell when the layer has no visible
1946 * non-transparent regions and can be removed from the layer list. It
1947 * does not affect the visibleRegion of this layer or any layers
1948 * beneath it. The hint may not be correct if apps don't respect the
1949 * SurfaceView restrictions (which, sadly, some don't).
1950 */
1951 Region transparentRegion;
1952
1953
1954 // handle hidden surfaces by setting the visible region to empty
1955 if (CC_LIKELY(layer->isVisible())) {
1956 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001957 Rect bounds(layer->computeScreenBounds());
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001958 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001959 Transform tr = layer->getTransform();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001960 if (!visibleRegion.isEmpty()) {
1961 // Remove the transparent area from the visible region
1962 if (translucent) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001963 if (tr.preserveRects()) {
1964 // transform the transparent region
1965 transparentRegion = tr.transform(s.activeTransparentRegion);
1966 } else {
1967 // transformation too complex, can't do the
1968 // transparent region optimization.
1969 transparentRegion.clear();
1970 }
1971 }
1972
1973 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07001974 const int32_t layerOrientation = tr.getOrientation();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001975 if (s.alpha==255 && !translucent &&
1976 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1977 // the opaque region is the layer's footprint
1978 opaqueRegion = visibleRegion;
1979 }
1980 }
1981 }
1982
1983 // Clip the covered region to the visible region
1984 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1985
1986 // Update aboveCoveredLayers for next (lower) layer
1987 aboveCoveredLayers.orSelf(visibleRegion);
1988
1989 // subtract the opaque region covered by the layers above us
1990 visibleRegion.subtractSelf(aboveOpaqueLayers);
1991
1992 // compute this layer's dirty region
1993 if (layer->contentDirty) {
1994 // we need to invalidate the whole region
1995 dirty = visibleRegion;
1996 // as well, as the old visible region
1997 dirty.orSelf(layer->visibleRegion);
1998 layer->contentDirty = false;
1999 } else {
2000 /* compute the exposed region:
2001 * the exposed region consists of two components:
2002 * 1) what's VISIBLE now and was COVERED before
2003 * 2) what's EXPOSED now less what was EXPOSED before
2004 *
2005 * note that (1) is conservative, we start with the whole
2006 * visible region but only keep what used to be covered by
2007 * something -- which mean it may have been exposed.
2008 *
2009 * (2) handles areas that were not covered by anything but got
2010 * exposed because of a resize.
2011 */
2012 const Region newExposed = visibleRegion - coveredRegion;
2013 const Region oldVisibleRegion = layer->visibleRegion;
2014 const Region oldCoveredRegion = layer->coveredRegion;
2015 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2016 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
2017 }
2018 dirty.subtractSelf(aboveOpaqueLayers);
2019
2020 // accumulate to the screen dirty region
2021 outDirtyRegion.orSelf(dirty);
2022
2023 // Update aboveOpaqueLayers for next (lower) layer
2024 aboveOpaqueLayers.orSelf(opaqueRegion);
2025
2026 // Store the visible region in screen space
2027 layer->setVisibleRegion(visibleRegion);
2028 layer->setCoveredRegion(coveredRegion);
2029 layer->setVisibleNonTransparentRegion(
2030 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002031 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002032
2033 outOpaqueRegion = aboveOpaqueLayers;
2034}
2035
2036void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2037 const Region& dirty) {
2038 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2039 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2040 if (hw->getLayerStack() == layerStack) {
2041 hw->dirtyRegion.orSelf(dirty);
2042 }
2043 }
2044}
2045
2046bool SurfaceFlinger::handlePageFlip()
2047{
Brian Andersond6927fb2016-07-23 23:37:30 -07002048 nsecs_t latchTime = systemTime();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002049 Region dirtyRegion;
2050
2051 bool visibleRegions = false;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002052 bool frameQueued = false;
2053
2054 // Store the set of layers that need updates. This set must not change as
2055 // buffers are being latched, as this could result in a deadlock.
2056 // Example: Two producers share the same command stream and:
2057 // 1.) Layer 0 is latched
2058 // 2.) Layer 0 gets a new frame
2059 // 2.) Layer 1 gets a new frame
2060 // 3.) Layer 1 is latched.
2061 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2062 // second frame. But layer 0's second frame could be waiting on display.
2063 Vector<Layer*> layersWithQueuedFrames;
Robert Carr2047fae2016-11-28 14:09:09 -08002064 mDrawingState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002065 if (layer->hasQueuedFrame()) {
2066 frameQueued = true;
2067 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002068 layersWithQueuedFrames.push_back(layer);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002069 } else {
2070 layer->useEmptyDamage();
2071 }
2072 } else {
2073 layer->useEmptyDamage();
2074 }
Robert Carr2047fae2016-11-28 14:09:09 -08002075 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002076 for (size_t i = 0, count = layersWithQueuedFrames.size() ; i<count ; i++) {
2077 Layer* layer = layersWithQueuedFrames[i];
Brian Andersond6927fb2016-07-23 23:37:30 -07002078 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002079 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002080 invalidateLayerStack(layer->getLayerStack(), dirty);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002081 }
2082
2083 mVisibleRegionsDirty |= visibleRegions;
2084
2085 // If we will need to wake up at some time in the future to deal with a
2086 // queued frame that shouldn't be displayed during this vsync period, wake
2087 // up during the next vsync period to check again.
2088 if (frameQueued && layersWithQueuedFrames.empty()) {
2089 signalLayerUpdate();
2090 }
2091
2092 // Only continue with the refresh if there is actually new work to do
2093 return !layersWithQueuedFrames.empty();
2094}
2095
2096void SurfaceFlinger::invalidateHwcGeometry()
2097{
2098 mHwWorkListDirty = true;
2099}
2100
2101
2102void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
2103 const Region& inDirtyRegion)
2104{
2105 // We only need to actually compose the display if:
2106 // 1) It is being handled by hardware composer, which may need this to
2107 // keep its virtual display state machine in sync, or
2108 // 2) There is work to be done (the dirty region isn't empty)
2109 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
2110 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
2111 return;
2112 }
2113
2114 Region dirtyRegion(inDirtyRegion);
2115
2116 // compute the invalid region
2117 hw->swapRegion.orSelf(dirtyRegion);
2118
2119 uint32_t flags = hw->getFlags();
2120 if (flags & DisplayDevice::SWAP_RECTANGLE) {
2121 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2122 // takes a rectangle, we must make sure to update that whole
2123 // rectangle in that case
2124 dirtyRegion.set(hw->swapRegion.bounds());
2125 } else {
2126 if (flags & DisplayDevice::PARTIAL_UPDATES) {
2127 // We need to redraw the rectangle that will be updated
2128 // (pushed to the framebuffer).
2129 // This is needed because PARTIAL_UPDATES only takes one
2130 // rectangle instead of a region (see DisplayDevice::flip())
2131 dirtyRegion.set(hw->swapRegion.bounds());
2132 } else {
2133 // we need to redraw everything (the whole screen)
2134 dirtyRegion.set(hw->bounds());
2135 hw->swapRegion = dirtyRegion;
2136 }
2137 }
2138
2139 if (CC_LIKELY(!mDaltonize && !mHasColorMatrix)) {
2140 if (!doComposeSurfaces(hw, dirtyRegion)) return;
2141 } else {
2142 RenderEngine& engine(getRenderEngine());
2143 mat4 colorMatrix = mColorMatrix;
2144 if (mDaltonize) {
2145 colorMatrix = colorMatrix * mDaltonizer();
2146 }
2147 mat4 oldMatrix = engine.setupColorTransform(colorMatrix);
2148 doComposeSurfaces(hw, dirtyRegion);
2149 engine.setupColorTransform(oldMatrix);
2150 }
2151
2152 // update the swap region and clear the dirty region
2153 hw->swapRegion.orSelf(dirtyRegion);
2154
2155 // swap buffers (presentation)
2156 hw->swapBuffers(getHwComposer());
2157}
2158
2159bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
2160{
2161 RenderEngine& engine(getRenderEngine());
2162 const int32_t id = hw->getHwcDisplayId();
2163 HWComposer& hwc(getHwComposer());
2164 HWComposer::LayerListIterator cur = hwc.begin(id);
2165 const HWComposer::LayerListIterator end = hwc.end(id);
2166
2167 bool hasGlesComposition = hwc.hasGlesComposition(id);
2168 if (hasGlesComposition) {
2169 if (!hw->makeCurrent(mEGLDisplay, mEGLContext)) {
2170 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
2171 hw->getDisplayName().string());
2172 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2173 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2174 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2175 }
2176 return false;
2177 }
2178
2179 // Never touch the framebuffer if we don't have any framebuffer layers
2180 const bool hasHwcComposition = hwc.hasHwcComposition(id);
2181 if (hasHwcComposition) {
2182 // when using overlays, we assume a fully transparent framebuffer
2183 // NOTE: we could reduce how much we need to clear, for instance
2184 // remove where there are opaque FB layers. however, on some
2185 // GPUs doing a "clean slate" clear might be more efficient.
2186 // We'll revisit later if needed.
2187 engine.clearWithColor(0, 0, 0, 0);
2188 } else {
2189 // we start with the whole screen area
2190 const Region bounds(hw->getBounds());
2191
2192 // we remove the scissor part
2193 // we're left with the letterbox region
2194 // (common case is that letterbox ends-up being empty)
2195 const Region letterbox(bounds.subtract(hw->getScissor()));
2196
2197 // compute the area to clear
2198 Region region(hw->undefinedRegion.merge(letterbox));
2199
2200 // but limit it to the dirty region
2201 region.andSelf(dirty);
2202
2203 // screen is already cleared here
2204 if (!region.isEmpty()) {
2205 // can happen with SurfaceView
2206 drawWormhole(hw, region);
2207 }
2208 }
2209
2210 if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
2211 // just to be on the safe side, we don't set the
2212 // scissor on the main display. It should never be needed
2213 // anyways (though in theory it could since the API allows it).
2214 const Rect& bounds(hw->getBounds());
2215 const Rect& scissor(hw->getScissor());
2216 if (scissor != bounds) {
2217 // scissor doesn't match the screen's dimensions, so we
2218 // need to clear everything outside of it and enable
2219 // the GL scissor so we don't draw anything where we shouldn't
2220
2221 // enable scissor for this frame
2222 const uint32_t height = hw->getHeight();
2223 engine.setScissor(scissor.left, height - scissor.bottom,
2224 scissor.getWidth(), scissor.getHeight());
2225 }
2226 }
2227 }
2228
2229 /*
2230 * and then, render the layers targeted at the framebuffer
2231 */
2232
2233 const Vector< sp<Layer> >& layers(hw->getVisibleLayersSortedByZ());
2234 const size_t count = layers.size();
2235 const Transform& tr = hw->getTransform();
2236 if (cur != end) {
2237 // we're using h/w composer
2238 for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
2239 const sp<Layer>& layer(layers[i]);
2240 const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
2241 if (!clip.isEmpty()) {
2242 switch (cur->getCompositionType()) {
2243 case HWC_CURSOR_OVERLAY:
2244 case HWC_OVERLAY: {
2245 const Layer::State& state(layer->getDrawingState());
2246 if ((cur->getHints() & HWC_HINT_CLEAR_FB)
2247 && i
2248 && layer->isOpaque(state) && (state.alpha == 0xFF)
2249 && hasGlesComposition) {
2250 // never clear the very first layer since we're
2251 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002252 layer->clearWithOpenGL(hw);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002253 }
2254 break;
2255 }
2256 case HWC_FRAMEBUFFER: {
2257 layer->draw(hw, clip);
2258 break;
2259 }
2260 case HWC_FRAMEBUFFER_TARGET: {
2261 // this should not happen as the iterator shouldn't
2262 // let us get there.
2263 ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%zu)", i);
2264 break;
2265 }
2266 }
2267 }
2268 layer->setAcquireFence(hw, *cur);
2269 }
2270 } else {
2271 // we're not using h/w composer
2272 for (size_t i=0 ; i<count ; ++i) {
2273 const sp<Layer>& layer(layers[i]);
2274 const Region clip(dirty.intersect(
2275 tr.transform(layer->visibleRegion)));
2276 if (!clip.isEmpty()) {
2277 layer->draw(hw, clip);
2278 }
2279 }
2280 }
2281
2282 // disable scissor at the end of the frame
2283 engine.disableScissor();
2284 return true;
2285}
2286
2287void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
2288 const int32_t height = hw->getHeight();
2289 RenderEngine& engine(getRenderEngine());
2290 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
2291}
2292
2293status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
2294 const sp<IBinder>& handle,
2295 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002296 const sp<Layer>& lbc,
2297 const sp<Layer>& parent)
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002298{
2299 // add this layer to the current state list
2300 {
2301 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002302 if (mNumLayers >= MAX_LAYERS) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002303 return NO_MEMORY;
2304 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002305 if (parent == nullptr) {
2306 mCurrentState.layersSortedByZ.add(lbc);
2307 } else {
2308 parent->addChild(lbc);
2309 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002310 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002311 mLayersAdded = true;
2312 mNumLayers++;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002313 }
2314
2315 // attach this layer to the client
2316 client->attachLayer(handle, lbc);
2317
2318 return NO_ERROR;
2319}
2320
2321status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) {
2322 Mutex::Autolock _l(mStateLock);
2323 sp<Layer> layer = weakLayer.promote();
2324 if (layer == nullptr) {
2325 // The layer has already been removed, carry on
2326 return NO_ERROR;
2327 }
2328
Robert Carr1f0a16a2016-10-24 16:27:39 -07002329 const auto& p = layer->getParent();
2330 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2331 mCurrentState.layersSortedByZ.remove(layer);
2332
Robert Carr136e2f62017-02-08 17:54:29 -08002333 // As a matter of normal operation, the LayerCleaner will produce a second
2334 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2335 // so we will succeed in promoting it, but it's already been removed
2336 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2337 // otherwise something has gone wrong and we are leaking the layer.
2338 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002339 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2340 layer->getName().string(),
2341 (p != nullptr) ? p->getName().string() : "no-parent");
2342 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002343 } else if (index < 0) {
2344 return NO_ERROR;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002345 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002346
2347 mLayersPendingRemoval.add(layer);
2348 mLayersRemoved = true;
2349 mNumLayers--;
2350 setTransactionFlags(eTransactionNeeded);
2351 return NO_ERROR;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002352}
2353
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002354uint32_t SurfaceFlinger::peekTransactionFlags() {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002355 return android_atomic_release_load(&mTransactionFlags);
2356}
2357
2358uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
2359 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2360}
2361
2362uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
2363 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2364 if ((old & flags)==0) { // wake the server up
2365 signalTransaction();
2366 }
2367 return old;
2368}
2369
2370void SurfaceFlinger::setTransactionState(
2371 const Vector<ComposerState>& state,
2372 const Vector<DisplayState>& displays,
2373 uint32_t flags)
2374{
2375 ATRACE_CALL();
2376 Mutex::Autolock _l(mStateLock);
2377 uint32_t transactionFlags = 0;
2378
2379 if (flags & eAnimation) {
2380 // For window updates that are part of an animation we must wait for
2381 // previous animation "frames" to be handled.
2382 while (mAnimTransactionPending) {
2383 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2384 if (CC_UNLIKELY(err != NO_ERROR)) {
2385 // just in case something goes wrong in SF, return to the
2386 // caller after a few seconds.
2387 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2388 "waiting for previous animation frame");
2389 mAnimTransactionPending = false;
2390 break;
2391 }
2392 }
2393 }
2394
2395 size_t count = displays.size();
2396 for (size_t i=0 ; i<count ; i++) {
2397 const DisplayState& s(displays[i]);
2398 transactionFlags |= setDisplayStateLocked(s);
2399 }
2400
2401 count = state.size();
2402 for (size_t i=0 ; i<count ; i++) {
2403 const ComposerState& s(state[i]);
2404 // Here we need to check that the interface we're given is indeed
2405 // one of our own. A malicious client could give us a NULL
2406 // IInterface, or one of its own or even one of our own but a
2407 // different type. All these situations would cause us to crash.
2408 //
2409 // NOTE: it would be better to use RTTI as we could directly check
2410 // that we have a Client*. however, RTTI is disabled in Android.
2411 if (s.client != NULL) {
2412 sp<IBinder> binder = IInterface::asBinder(s.client);
2413 if (binder != NULL) {
Fabien Sanglard45b20252017-01-18 16:43:18 -08002414 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002415 sp<Client> client( static_cast<Client *>(s.client.get()) );
2416 transactionFlags |= setClientStateLocked(client, s.state);
2417 }
2418 }
2419 }
2420 }
2421
2422 // If a synchronous transaction is explicitly requested without any changes,
2423 // force a transaction anyway. This can be used as a flush mechanism for
2424 // previous async transactions.
2425 if (transactionFlags == 0 && (flags & eSynchronous)) {
2426 transactionFlags = eTransactionNeeded;
2427 }
2428
2429 if (transactionFlags) {
2430 if (mInterceptor.isEnabled()) {
2431 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2432 }
2433
2434 // this triggers the transaction
2435 setTransactionFlags(transactionFlags);
2436
2437 // if this is a synchronous transaction, wait for it to take effect
2438 // before returning.
2439 if (flags & eSynchronous) {
2440 mTransactionPending = true;
2441 }
2442 if (flags & eAnimation) {
2443 mAnimTransactionPending = true;
2444 }
2445 while (mTransactionPending) {
2446 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2447 if (CC_UNLIKELY(err != NO_ERROR)) {
2448 // just in case something goes wrong in SF, return to the
2449 // called after a few seconds.
2450 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2451 mTransactionPending = false;
2452 break;
2453 }
2454 }
2455 }
2456}
2457
2458uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2459{
2460 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2461 if (dpyIdx < 0)
2462 return 0;
2463
2464 uint32_t flags = 0;
2465 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
2466 if (disp.isValid()) {
2467 const uint32_t what = s.what;
2468 if (what & DisplayState::eSurfaceChanged) {
2469 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
2470 disp.surface = s.surface;
2471 flags |= eDisplayTransactionNeeded;
2472 }
2473 }
2474 if (what & DisplayState::eLayerStackChanged) {
2475 if (disp.layerStack != s.layerStack) {
2476 disp.layerStack = s.layerStack;
2477 flags |= eDisplayTransactionNeeded;
2478 }
2479 }
2480 if (what & DisplayState::eDisplayProjectionChanged) {
2481 if (disp.orientation != s.orientation) {
2482 disp.orientation = s.orientation;
2483 flags |= eDisplayTransactionNeeded;
2484 }
2485 if (disp.frame != s.frame) {
2486 disp.frame = s.frame;
2487 flags |= eDisplayTransactionNeeded;
2488 }
2489 if (disp.viewport != s.viewport) {
2490 disp.viewport = s.viewport;
2491 flags |= eDisplayTransactionNeeded;
2492 }
2493 }
2494 if (what & DisplayState::eDisplaySizeChanged) {
2495 if (disp.width != s.width) {
2496 disp.width = s.width;
2497 flags |= eDisplayTransactionNeeded;
2498 }
2499 if (disp.height != s.height) {
2500 disp.height = s.height;
2501 flags |= eDisplayTransactionNeeded;
2502 }
2503 }
2504 }
2505 return flags;
2506}
2507
2508uint32_t SurfaceFlinger::setClientStateLocked(
2509 const sp<Client>& client,
2510 const layer_state_t& s)
2511{
2512 uint32_t flags = 0;
2513 sp<Layer> layer(client->getLayerUser(s.surface));
2514 if (layer != 0) {
2515 const uint32_t what = s.what;
2516 bool geometryAppliesWithResize =
2517 what & layer_state_t::eGeometryAppliesWithResize;
2518 if (what & layer_state_t::ePositionChanged) {
2519 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
2520 flags |= eTraversalNeeded;
2521 }
2522 }
2523 if (what & layer_state_t::eLayerChanged) {
2524 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002525 const auto& p = layer->getParent();
2526 if (p == nullptr) {
2527 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2528 if (layer->setLayer(s.z) && idx >= 0) {
2529 mCurrentState.layersSortedByZ.removeAt(idx);
2530 mCurrentState.layersSortedByZ.add(layer);
2531 // we need traversal (state changed)
2532 // AND transaction (list changed)
2533 flags |= eTransactionNeeded|eTraversalNeeded;
2534 }
2535 } else {
2536 if (p->setChildLayer(layer, s.z)) {
2537 flags |= eTransactionNeeded|eTraversalNeeded;
2538 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002539 }
2540 }
2541 if (what & layer_state_t::eSizeChanged) {
2542 if (layer->setSize(s.w, s.h)) {
2543 flags |= eTraversalNeeded;
2544 }
2545 }
2546 if (what & layer_state_t::eAlphaChanged) {
2547 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
2548 flags |= eTraversalNeeded;
2549 }
2550 if (what & layer_state_t::eMatrixChanged) {
2551 if (layer->setMatrix(s.matrix))
2552 flags |= eTraversalNeeded;
2553 }
2554 if (what & layer_state_t::eTransparentRegionChanged) {
2555 if (layer->setTransparentRegionHint(s.transparentRegion))
2556 flags |= eTraversalNeeded;
2557 }
2558 if (what & layer_state_t::eFlagsChanged) {
2559 if (layer->setFlags(s.flags, s.mask))
2560 flags |= eTraversalNeeded;
2561 }
2562 if (what & layer_state_t::eCropChanged) {
2563 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
2564 flags |= eTraversalNeeded;
2565 }
2566 if (what & layer_state_t::eFinalCropChanged) {
2567 if (layer->setFinalCrop(s.finalCrop))
2568 flags |= eTraversalNeeded;
2569 }
2570 if (what & layer_state_t::eLayerStackChanged) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002571 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002572 // We only allow setting layer stacks for top level layers,
2573 // everything else inherits layer stack from its parent.
2574 if (layer->hasParent()) {
2575 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2576 layer->getName().string());
2577 } else if (idx < 0) {
2578 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2579 "that also does not appear in the top level layer list. Something"
2580 " has gone wrong.", layer->getName().string());
2581 } else if (layer->setLayerStack(s.layerStack)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002582 mCurrentState.layersSortedByZ.removeAt(idx);
2583 mCurrentState.layersSortedByZ.add(layer);
2584 // we need traversal (state changed)
2585 // AND transaction (list changed)
2586 flags |= eTransactionNeeded|eTraversalNeeded;
2587 }
2588 }
2589 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08002590 if (s.barrierHandle != nullptr) {
2591 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
2592 } else if (s.barrierGbp != nullptr) {
2593 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
2594 if (authenticateSurfaceTextureLocked(gbp)) {
2595 const auto& otherLayer =
2596 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
2597 layer->deferTransactionUntil(otherLayer, s.frameNumber);
2598 } else {
2599 ALOGE("Attempt to defer transaction to to an"
2600 " unrecognized GraphicBufferProducer");
2601 }
2602 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002603 // We don't trigger a traversal here because if no other state is
2604 // changed, we don't want this to cause any more work
2605 }
Robert Carr1db73f62016-12-21 12:58:51 -08002606 if (what & layer_state_t::eReparentChildren) {
2607 if (layer->reparentChildren(s.reparentHandle)) {
2608 flags |= eTransactionNeeded|eTraversalNeeded;
2609 }
2610 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002611 if (what & layer_state_t::eOverrideScalingModeChanged) {
2612 layer->setOverrideScalingMode(s.overrideScalingMode);
2613 // We don't trigger a traversal here because if no other state is
2614 // changed, we don't want this to cause any more work
2615 }
2616 }
2617 return flags;
2618}
2619
2620status_t SurfaceFlinger::createLayer(
2621 const String8& name,
2622 const sp<Client>& client,
2623 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002624 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2625 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002626{
2627 if (int32_t(w|h) < 0) {
2628 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
2629 int(w), int(h));
2630 return BAD_VALUE;
2631 }
2632
2633 status_t result = NO_ERROR;
2634
2635 sp<Layer> layer;
2636
2637 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2638 case ISurfaceComposerClient::eFXSurfaceNormal:
2639 result = createNormalLayer(client,
2640 name, w, h, flags, format,
2641 handle, gbp, &layer);
2642 break;
2643 case ISurfaceComposerClient::eFXSurfaceDim:
2644 result = createDimLayer(client,
2645 name, w, h, flags,
2646 handle, gbp, &layer);
2647 break;
2648 default:
2649 result = BAD_VALUE;
2650 break;
2651 }
2652
2653 if (result != NO_ERROR) {
2654 return result;
2655 }
2656
Albert Chaulk479c60c2017-01-27 14:21:34 -05002657 layer->setInfo(windowType, ownerUid);
2658
Robert Carr1f0a16a2016-10-24 16:27:39 -07002659 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002660 if (result != NO_ERROR) {
2661 return result;
2662 }
2663 mInterceptor.saveSurfaceCreation(layer);
2664
2665 setTransactionFlags(eTransactionNeeded);
2666 return result;
2667}
2668
2669status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2670 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2671 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2672{
2673 // initialize the surfaces
2674 switch (format) {
2675 case PIXEL_FORMAT_TRANSPARENT:
2676 case PIXEL_FORMAT_TRANSLUCENT:
2677 format = PIXEL_FORMAT_RGBA_8888;
2678 break;
2679 case PIXEL_FORMAT_OPAQUE:
2680 format = PIXEL_FORMAT_RGBX_8888;
2681 break;
2682 }
2683
2684 *outLayer = new Layer(this, client, name, w, h, flags);
2685 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2686 if (err == NO_ERROR) {
2687 *handle = (*outLayer)->getHandle();
2688 *gbp = (*outLayer)->getProducer();
2689 }
2690
2691 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2692 return err;
2693}
2694
2695status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2696 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2697 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2698{
2699 *outLayer = new LayerDim(this, client, name, w, h, flags);
2700 *handle = (*outLayer)->getHandle();
2701 *gbp = (*outLayer)->getProducer();
2702 return NO_ERROR;
2703}
2704
2705status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
2706{
2707 // called by the window manager when it wants to remove a Layer
2708 status_t err = NO_ERROR;
2709 sp<Layer> l(client->getLayerUser(handle));
2710 if (l != NULL) {
2711 mInterceptor.saveSurfaceDeletion(l);
2712 err = removeLayer(l);
2713 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2714 "error removing layer=%p (%s)", l.get(), strerror(-err));
2715 }
2716 return err;
2717}
2718
2719status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
2720{
2721 // called by ~LayerCleaner() when all references to the IBinder (handle)
2722 // are gone
2723 return removeLayer(layer);
2724}
2725
2726// ---------------------------------------------------------------------------
2727
2728void SurfaceFlinger::onInitializeDisplays() {
2729 // reset screen orientation and use primary layer stack
2730 Vector<ComposerState> state;
2731 Vector<DisplayState> displays;
2732 DisplayState d;
2733 d.what = DisplayState::eDisplayProjectionChanged |
2734 DisplayState::eLayerStackChanged;
2735 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
2736 d.layerStack = 0;
2737 d.orientation = DisplayState::eOrientationDefault;
2738 d.frame.makeInvalid();
2739 d.viewport.makeInvalid();
2740 d.width = 0;
2741 d.height = 0;
2742 displays.add(d);
2743 setTransactionState(state, displays, 0);
2744 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
2745
2746 const nsecs_t period =
2747 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2748 mAnimFrameTracker.setDisplayRefreshPeriod(period);
2749}
2750
2751void SurfaceFlinger::initializeDisplays() {
2752 class MessageScreenInitialized : public MessageBase {
2753 SurfaceFlinger* flinger;
2754 public:
2755 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2756 virtual bool handler() {
2757 flinger->onInitializeDisplays();
2758 return true;
2759 }
2760 };
2761 sp<MessageBase> msg = new MessageScreenInitialized(this);
2762 postMessageAsync(msg); // we may be called from main thread, use async message
2763}
2764
2765void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2766 int mode) {
2767 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2768 this);
2769 int32_t type = hw->getDisplayType();
2770 int currentMode = hw->getPowerMode();
2771
2772 if (mode == currentMode) {
2773 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
2774 return;
2775 }
2776
2777 hw->setPowerMode(mode);
2778 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2779 ALOGW("Trying to set power mode for virtual display");
2780 return;
2781 }
2782
2783 if (mInterceptor.isEnabled()) {
2784 Mutex::Autolock _l(mStateLock);
2785 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
2786 if (idx < 0) {
2787 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
2788 return;
2789 }
2790 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
2791 }
2792
2793 if (currentMode == HWC_POWER_MODE_OFF) {
2794 // Turn on the display
2795 getHwComposer().setPowerMode(type, mode);
2796 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2797 // FIXME: eventthread only knows about the main display right now
2798 mEventThread->onScreenAcquired();
2799 resyncToHardwareVsync(true);
2800 }
2801
2802 mVisibleRegionsDirty = true;
2803 mHasPoweredOff = true;
2804 repaintEverything();
2805
2806 struct sched_param param = {0};
2807 param.sched_priority = 1;
2808 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
2809 ALOGW("Couldn't set SCHED_FIFO on display on");
2810 }
2811 } else if (mode == HWC_POWER_MODE_OFF) {
2812 // Turn off the display
2813 struct sched_param param = {0};
2814 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
2815 ALOGW("Couldn't set SCHED_OTHER on display off");
2816 }
2817
2818 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2819 disableHardwareVsync(true); // also cancels any in-progress resync
2820
2821 // FIXME: eventthread only knows about the main display right now
2822 mEventThread->onScreenReleased();
2823 }
2824
2825 getHwComposer().setPowerMode(type, mode);
2826 mVisibleRegionsDirty = true;
2827 // from this point on, SF will stop drawing on this display
2828 } else {
2829 getHwComposer().setPowerMode(type, mode);
2830 }
2831}
2832
2833void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2834 class MessageSetPowerMode: public MessageBase {
2835 SurfaceFlinger& mFlinger;
2836 sp<IBinder> mDisplay;
2837 int mMode;
2838 public:
2839 MessageSetPowerMode(SurfaceFlinger& flinger,
2840 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2841 mDisplay(disp) { mMode = mode; }
2842 virtual bool handler() {
2843 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2844 if (hw == NULL) {
2845 ALOGE("Attempt to set power mode = %d for null display %p",
2846 mMode, mDisplay.get());
2847 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2848 ALOGW("Attempt to set power mode = %d for virtual display",
2849 mMode);
2850 } else {
2851 mFlinger.setPowerModeInternal(hw, mMode);
2852 }
2853 return true;
2854 }
2855 };
2856 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
2857 postMessageSync(msg);
2858}
2859
2860// ---------------------------------------------------------------------------
2861
2862status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2863{
2864 String8 result;
2865
2866 IPCThreadState* ipc = IPCThreadState::self();
2867 const int pid = ipc->getCallingPid();
2868 const int uid = ipc->getCallingUid();
2869 if ((uid != AID_SHELL) &&
2870 !PermissionCache::checkPermission(sDump, pid, uid)) {
2871 result.appendFormat("Permission Denial: "
2872 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
2873 } else {
2874 // Try to get the main lock, but give up after one second
2875 // (this would indicate SF is stuck, but we want to be able to
2876 // print something in dumpsys).
2877 status_t err = mStateLock.timedLock(s2ns(1));
2878 bool locked = (err == NO_ERROR);
2879 if (!locked) {
2880 result.appendFormat(
2881 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2882 "dumping anyways (no locks held)\n", strerror(-err), err);
2883 }
2884
2885 bool dumpAll = true;
2886 size_t index = 0;
2887 size_t numArgs = args.size();
2888 if (numArgs) {
2889 if ((index < numArgs) &&
2890 (args[index] == String16("--list"))) {
2891 index++;
2892 listLayersLocked(args, index, result);
2893 dumpAll = false;
2894 }
2895
2896 if ((index < numArgs) &&
2897 (args[index] == String16("--latency"))) {
2898 index++;
2899 dumpStatsLocked(args, index, result);
2900 dumpAll = false;
2901 }
2902
2903 if ((index < numArgs) &&
2904 (args[index] == String16("--latency-clear"))) {
2905 index++;
2906 clearStatsLocked(args, index, result);
2907 dumpAll = false;
2908 }
2909
2910 if ((index < numArgs) &&
2911 (args[index] == String16("--dispsync"))) {
2912 index++;
2913 mPrimaryDispSync.dump(result);
2914 dumpAll = false;
2915 }
2916
2917 if ((index < numArgs) &&
2918 (args[index] == String16("--static-screen"))) {
2919 index++;
2920 dumpStaticScreenStats(result);
2921 dumpAll = false;
2922 }
2923
2924 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07002925 (args[index] == String16("--frame-events"))) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002926 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07002927 dumpFrameEventsLocked(result);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002928 dumpAll = false;
2929 }
2930 }
2931
2932 if (dumpAll) {
2933 dumpAllLocked(args, index, result);
2934 }
2935
2936 if (locked) {
2937 mStateLock.unlock();
2938 }
2939 }
2940 write(fd, result.string(), result.size());
2941 return NO_ERROR;
2942}
2943
2944void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2945 size_t& /* index */, String8& result) const
2946{
Robert Carr2047fae2016-11-28 14:09:09 -08002947 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002948 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08002949 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002950}
2951
2952void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2953 String8& result) const
2954{
2955 String8 name;
2956 if (index < args.size()) {
2957 name = String8(args[index]);
2958 index++;
2959 }
2960
2961 const nsecs_t period =
2962 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2963 result.appendFormat("%" PRId64 "\n", period);
2964
2965 if (name.isEmpty()) {
2966 mAnimFrameTracker.dumpStats(result);
2967 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08002968 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002969 if (name == layer->getName()) {
2970 layer->dumpFrameStats(result);
2971 }
Robert Carr2047fae2016-11-28 14:09:09 -08002972 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002973 }
2974}
2975
2976void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2977 String8& /* result */)
2978{
2979 String8 name;
2980 if (index < args.size()) {
2981 name = String8(args[index]);
2982 index++;
2983 }
2984
Robert Carr2047fae2016-11-28 14:09:09 -08002985 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002986 if (name.isEmpty() || (name == layer->getName())) {
2987 layer->clearFrameStats();
2988 }
Robert Carr2047fae2016-11-28 14:09:09 -08002989 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002990
2991 mAnimFrameTracker.clearStats();
2992}
2993
2994// This should only be called from the main thread. Otherwise it would need
2995// the lock and should use mCurrentState rather than mDrawingState.
2996void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08002997 mDrawingState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002998 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08002999 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003000
3001 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3002}
3003
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003004void SurfaceFlinger::appendSfConfigString(String8& result) const
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003005{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003006 result.append(" [sf");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003007#ifdef HAS_CONTEXT_PRIORITY
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003008 result.append(" HAS_CONTEXT_PRIORITY");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003009#endif
3010#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003011 result.append(" NEVER_DEFAULT_TO_ASYNC_MODE");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003012#endif
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003013 if (isLayerTripleBufferingDisabled())
3014 result.append(" DISABLE_TRIPLE_BUFFERING");
3015 result.append("]");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003016}
3017
3018void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3019{
3020 result.appendFormat("Static screen stats:\n");
3021 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3022 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3023 float percent = 100.0f *
3024 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3025 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3026 b + 1, bucketTimeSec, percent);
3027 }
3028 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3029 float percent = 100.0f *
3030 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3031 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3032 NUM_BUCKETS - 1, bucketTimeSec, percent);
3033}
3034
Brian Andersond6927fb2016-07-23 23:37:30 -07003035void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3036 result.appendFormat("Layer frame timestamps:\n");
3037
3038 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3039 const size_t count = currentLayers.size();
3040 for (size_t i=0 ; i<count ; i++) {
3041 currentLayers[i]->dumpFrameEvents(result);
3042 }
3043}
3044
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003045void SurfaceFlinger::recordBufferingStats(const char* layerName,
3046 std::vector<OccupancyTracker::Segment>&& history) {
3047 Mutex::Autolock lock(mBufferingStatsMutex);
3048 auto& stats = mBufferingStats[layerName];
3049 for (const auto& segment : history) {
3050 if (!segment.usedThirdBuffer) {
3051 stats.twoBufferTime += segment.totalTime;
3052 }
3053 if (segment.occupancyAverage < 1.0f) {
3054 stats.doubleBufferedTime += segment.totalTime;
3055 } else if (segment.occupancyAverage < 2.0f) {
3056 stats.tripleBufferedTime += segment.totalTime;
3057 }
3058 ++stats.numSegments;
3059 stats.totalTime += segment.totalTime;
3060 }
3061}
3062
3063void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3064 result.append("Buffering stats:\n");
3065 result.append(" [Layer name] <Active time> <Two buffer> "
3066 "<Double buffered> <Triple buffered>\n");
3067 Mutex::Autolock lock(mBufferingStatsMutex);
3068 typedef std::tuple<std::string, float, float, float> BufferTuple;
3069 std::map<float, BufferTuple, std::greater<float>> sorted;
3070 for (const auto& statsPair : mBufferingStats) {
3071 const char* name = statsPair.first.c_str();
3072 const BufferingStats& stats = statsPair.second;
3073 if (stats.numSegments == 0) {
3074 continue;
3075 }
3076 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3077 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3078 stats.totalTime;
3079 float doubleBufferRatio = static_cast<float>(
3080 stats.doubleBufferedTime) / stats.totalTime;
3081 float tripleBufferRatio = static_cast<float>(
3082 stats.tripleBufferedTime) / stats.totalTime;
3083 sorted.insert({activeTime, {name, twoBufferRatio,
3084 doubleBufferRatio, tripleBufferRatio}});
3085 }
3086 for (const auto& sortedPair : sorted) {
3087 float activeTime = sortedPair.first;
3088 const BufferTuple& values = sortedPair.second;
3089 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3090 std::get<0>(values).c_str(), activeTime,
3091 std::get<1>(values), std::get<2>(values),
3092 std::get<3>(values));
3093 }
3094 result.append("\n");
3095}
3096
3097void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3098 String8& result) const
3099{
3100 bool colorize = false;
3101 if (index < args.size()
3102 && (args[index] == String16("--color"))) {
3103 colorize = true;
3104 index++;
3105 }
3106
3107 Colorizer colorizer(colorize);
3108
3109 // figure out if we're stuck somewhere
3110 const nsecs_t now = systemTime();
3111 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3112 const nsecs_t inTransaction(mDebugInTransaction);
3113 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3114 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3115
3116 /*
3117 * Dump library configuration.
3118 */
3119
3120 colorizer.bold(result);
3121 result.append("Build configuration:");
3122 colorizer.reset(result);
3123 appendSfConfigString(result);
3124 appendUiConfigString(result);
3125 appendGuiConfigString(result);
3126 result.append("\n");
3127
3128 colorizer.bold(result);
3129 result.append("Sync configuration: ");
3130 colorizer.reset(result);
3131 result.append(SyncFeatures::getInstance().toString());
3132 result.append("\n");
3133
3134 colorizer.bold(result);
3135 result.append("DispSync configuration: ");
3136 colorizer.reset(result);
3137 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3138 "present offset %d ns (refresh %" PRId64 " ns)",
3139 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, PRESENT_TIME_OFFSET_FROM_VSYNC_NS,
3140 mHwc->getRefreshPeriod(HWC_DISPLAY_PRIMARY));
3141 result.append("\n");
3142
3143 // Dump static screen stats
3144 result.append("\n");
3145 dumpStaticScreenStats(result);
3146 result.append("\n");
3147
3148 dumpBufferingStats(result);
3149
3150 /*
3151 * Dump the visible layer list
3152 */
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003153 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003154 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003155 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003156 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003157 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003158 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003159
3160 /*
3161 * Dump Display state
3162 */
3163
3164 colorizer.bold(result);
3165 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
3166 colorizer.reset(result);
3167 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3168 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
3169 hw->dump(result);
3170 }
3171
3172 /*
3173 * Dump SurfaceFlinger global state
3174 */
3175
3176 colorizer.bold(result);
3177 result.append("SurfaceFlinger global state:\n");
3178 colorizer.reset(result);
3179
3180 HWComposer& hwc(getHwComposer());
3181 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3182
3183 colorizer.bold(result);
3184 result.appendFormat("EGL implementation : %s\n",
3185 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3186 colorizer.reset(result);
3187 result.appendFormat("%s\n",
3188 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
3189
3190 mRenderEngine->dump(result);
3191
3192 hw->undefinedRegion.dump(result, "undefinedRegion");
3193 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3194 hw->getOrientation(), hw->isDisplayOn());
3195 result.appendFormat(
3196 " last eglSwapBuffers() time: %f us\n"
3197 " last transaction time : %f us\n"
3198 " transaction-flags : %08x\n"
3199 " refresh-rate : %f fps\n"
3200 " x-dpi : %f\n"
3201 " y-dpi : %f\n"
3202 " gpu_to_cpu_unsupported : %d\n"
3203 ,
3204 mLastSwapBufferTime/1000.0,
3205 mLastTransactionTime/1000.0,
3206 mTransactionFlags,
3207 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
3208 hwc.getDpiX(HWC_DISPLAY_PRIMARY),
3209 hwc.getDpiY(HWC_DISPLAY_PRIMARY),
3210 !mGpuToCpuSupported);
3211
3212 result.appendFormat(" eglSwapBuffers time: %f us\n",
3213 inSwapBuffersDuration/1000.0);
3214
3215 result.appendFormat(" transaction time: %f us\n",
3216 inTransactionDuration/1000.0);
3217
3218 /*
3219 * VSYNC state
3220 */
3221 mEventThread->dump(result);
3222
3223 /*
3224 * Dump HWComposer state
3225 */
3226 colorizer.bold(result);
3227 result.append("h/w composer state:\n");
3228 colorizer.reset(result);
3229 result.appendFormat(" h/w composer %s and %s\n",
3230 hwc.initCheck()==NO_ERROR ? "present" : "not present",
3231 (mDebugDisableHWC || mDebugRegion || mDaltonize
3232 || mHasColorMatrix) ? "disabled" : "enabled");
3233 hwc.dump(result);
3234
3235 /*
3236 * Dump gralloc state
3237 */
3238 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3239 alloc.dump(result);
3240}
3241
3242const Vector< sp<Layer> >&
3243SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
3244 // Note: mStateLock is held here
3245 wp<IBinder> dpy;
3246 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3247 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3248 dpy = mDisplays.keyAt(i);
3249 break;
3250 }
3251 }
3252 if (dpy == NULL) {
3253 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3254 // Just use the primary display so we have something to return
3255 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3256 }
3257 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
3258}
3259
3260bool SurfaceFlinger::startDdmConnection()
3261{
3262 void* libddmconnection_dso =
3263 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3264 if (!libddmconnection_dso) {
3265 return false;
3266 }
3267 void (*DdmConnection_start)(const char* name);
3268 DdmConnection_start =
3269 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
3270 if (!DdmConnection_start) {
3271 dlclose(libddmconnection_dso);
3272 return false;
3273 }
3274 (*DdmConnection_start)(getServiceName());
3275 return true;
3276}
3277
3278status_t SurfaceFlinger::onTransact(
3279 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3280{
3281 switch (code) {
3282 case CREATE_CONNECTION:
3283 case CREATE_DISPLAY:
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003284 case BOOT_FINISHED:
3285 case CLEAR_ANIMATION_FRAME_STATS:
3286 case GET_ANIMATION_FRAME_STATS:
3287 case SET_POWER_MODE:
3288 case GET_HDR_CAPABILITIES:
3289 {
3290 // codes that require permission check
3291 IPCThreadState* ipc = IPCThreadState::self();
3292 const int pid = ipc->getCallingPid();
3293 const int uid = ipc->getCallingUid();
3294 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3295 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3296 ALOGE("Permission Denial: "
3297 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3298 return PERMISSION_DENIED;
3299 }
3300 break;
3301 }
Robert Carr1db73f62016-12-21 12:58:51 -08003302 /*
3303 * Calling setTransactionState is safe, because you need to have been
3304 * granted a reference to Client* and Handle* to do anything with it.
3305 *
3306 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3307 */
3308 case SET_TRANSACTION_STATE:
3309 case CREATE_SCOPED_CONNECTION:
3310 {
3311 break;
3312 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003313 case CAPTURE_SCREEN:
3314 {
3315 // codes that require permission check
3316 IPCThreadState* ipc = IPCThreadState::self();
3317 const int pid = ipc->getCallingPid();
3318 const int uid = ipc->getCallingUid();
3319 if ((uid != AID_GRAPHICS) &&
3320 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
3321 ALOGE("Permission Denial: "
3322 "can't read framebuffer pid=%d, uid=%d", pid, uid);
3323 return PERMISSION_DENIED;
3324 }
3325 break;
3326 }
3327 }
3328
3329 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3330 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
3331 CHECK_INTERFACE(ISurfaceComposer, data, reply);
3332 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
3333 IPCThreadState* ipc = IPCThreadState::self();
3334 const int pid = ipc->getCallingPid();
3335 const int uid = ipc->getCallingUid();
3336 ALOGE("Permission Denial: "
3337 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3338 return PERMISSION_DENIED;
3339 }
3340 int n;
3341 switch (code) {
3342 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
3343 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
3344 return NO_ERROR;
3345 case 1002: // SHOW_UPDATES
3346 n = data.readInt32();
3347 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
3348 invalidateHwcGeometry();
3349 repaintEverything();
3350 return NO_ERROR;
3351 case 1004:{ // repaint everything
3352 repaintEverything();
3353 return NO_ERROR;
3354 }
3355 case 1005:{ // force transaction
3356 setTransactionFlags(
3357 eTransactionNeeded|
3358 eDisplayTransactionNeeded|
3359 eTraversalNeeded);
3360 return NO_ERROR;
3361 }
3362 case 1006:{ // send empty update
3363 signalRefresh();
3364 return NO_ERROR;
3365 }
3366 case 1008: // toggle use of hw composer
3367 n = data.readInt32();
3368 mDebugDisableHWC = n ? 1 : 0;
3369 invalidateHwcGeometry();
3370 repaintEverything();
3371 return NO_ERROR;
3372 case 1009: // toggle use of transform hint
3373 n = data.readInt32();
3374 mDebugDisableTransformHint = n ? 1 : 0;
3375 invalidateHwcGeometry();
3376 repaintEverything();
3377 return NO_ERROR;
3378 case 1010: // interrogate.
3379 reply->writeInt32(0);
3380 reply->writeInt32(0);
3381 reply->writeInt32(mDebugRegion);
3382 reply->writeInt32(0);
3383 reply->writeInt32(mDebugDisableHWC);
3384 return NO_ERROR;
3385 case 1013: {
3386 Mutex::Autolock _l(mStateLock);
3387 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3388 reply->writeInt32(hw->getPageFlipCount());
3389 return NO_ERROR;
3390 }
3391 case 1014: {
3392 // daltonize
3393 n = data.readInt32();
3394 switch (n % 10) {
3395 case 1:
3396 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3397 break;
3398 case 2:
3399 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3400 break;
3401 case 3:
3402 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3403 break;
3404 }
3405 if (n >= 10) {
3406 mDaltonizer.setMode(ColorBlindnessMode::Correction);
3407 } else {
3408 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
3409 }
3410 mDaltonize = n > 0;
3411 invalidateHwcGeometry();
3412 repaintEverything();
3413 return NO_ERROR;
3414 }
3415 case 1015: {
3416 // apply a color matrix
3417 n = data.readInt32();
3418 mHasColorMatrix = n ? 1 : 0;
3419 if (n) {
3420 // color matrix is sent as mat3 matrix followed by vec3
3421 // offset, then packed into a mat4 where the last row is
3422 // the offset and extra values are 0
3423 for (size_t i = 0 ; i < 4; i++) {
3424 for (size_t j = 0; j < 4; j++) {
3425 mColorMatrix[i][j] = data.readFloat();
3426 }
3427 }
3428 } else {
3429 mColorMatrix = mat4();
3430 }
3431 invalidateHwcGeometry();
3432 repaintEverything();
3433 return NO_ERROR;
3434 }
3435 // This is an experimental interface
3436 // Needs to be shifted to proper binder interface when we productize
3437 case 1016: {
3438 n = data.readInt32();
3439 mPrimaryDispSync.setRefreshSkipCount(n);
3440 return NO_ERROR;
3441 }
3442 case 1017: {
3443 n = data.readInt32();
3444 mForceFullDamage = static_cast<bool>(n);
3445 return NO_ERROR;
3446 }
3447 case 1018: { // Modify Choreographer's phase offset
3448 n = data.readInt32();
3449 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3450 return NO_ERROR;
3451 }
3452 case 1019: { // Modify SurfaceFlinger's phase offset
3453 n = data.readInt32();
3454 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3455 return NO_ERROR;
3456 }
3457 case 1020: { // Layer updates interceptor
3458 n = data.readInt32();
3459 if (n) {
3460 ALOGV("Interceptor enabled");
3461 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
3462 }
3463 else{
3464 ALOGV("Interceptor disabled");
3465 mInterceptor.disable();
3466 }
3467 return NO_ERROR;
3468 }
3469 case 1021: { // Disable HWC virtual displays
3470 n = data.readInt32();
3471 mUseHwcVirtualDisplays = !n;
3472 return NO_ERROR;
3473 }
3474 }
3475 }
3476 return err;
3477}
3478
3479void SurfaceFlinger::repaintEverything() {
3480 android_atomic_or(1, &mRepaintEverything);
3481 signalTransaction();
3482}
3483
3484// ---------------------------------------------------------------------------
3485// Capture screen into an IGraphiBufferProducer
3486// ---------------------------------------------------------------------------
3487
3488/* The code below is here to handle b/8734824
3489 *
3490 * We create a IGraphicBufferProducer wrapper that forwards all calls
3491 * from the surfaceflinger thread to the calling binder thread, where they
3492 * are executed. This allows the calling thread in the calling process to be
3493 * reused and not depend on having "enough" binder threads to handle the
3494 * requests.
3495 */
3496class GraphicProducerWrapper : public BBinder, public MessageHandler {
3497 /* Parts of GraphicProducerWrapper are run on two different threads,
3498 * communicating by sending messages via Looper but also by shared member
3499 * data. Coherence maintenance is subtle and in places implicit (ugh).
3500 *
3501 * Don't rely on Looper's sendMessage/handleMessage providing
3502 * release/acquire semantics for any data not actually in the Message.
3503 * Data going from surfaceflinger to binder threads needs to be
3504 * synchronized explicitly.
3505 *
3506 * Barrier open/wait do provide release/acquire semantics. This provides
3507 * implicit synchronization for data coming back from binder to
3508 * surfaceflinger threads.
3509 */
3510
3511 sp<IGraphicBufferProducer> impl;
3512 sp<Looper> looper;
3513 status_t result;
3514 bool exitPending;
3515 bool exitRequested;
3516 Barrier barrier;
3517 uint32_t code;
3518 Parcel const* data;
3519 Parcel* reply;
3520
3521 enum {
3522 MSG_API_CALL,
3523 MSG_EXIT
3524 };
3525
3526 /*
3527 * Called on surfaceflinger thread. This is called by our "fake"
3528 * BpGraphicBufferProducer. We package the data and reply Parcel and
3529 * forward them to the binder thread.
3530 */
3531 virtual status_t transact(uint32_t code,
3532 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
3533 this->code = code;
3534 this->data = &data;
3535 this->reply = reply;
3536 if (exitPending) {
3537 // if we've exited, we run the message synchronously right here.
3538 // note (JH): as far as I can tell from looking at the code, this
3539 // never actually happens. if it does, i'm not sure if it happens
3540 // on the surfaceflinger or binder thread.
3541 handleMessage(Message(MSG_API_CALL));
3542 } else {
3543 barrier.close();
3544 // Prevent stores to this->{code, data, reply} from being
3545 // reordered later than the construction of Message.
3546 atomic_thread_fence(memory_order_release);
3547 looper->sendMessage(this, Message(MSG_API_CALL));
3548 barrier.wait();
3549 }
3550 return result;
3551 }
3552
3553 /*
3554 * here we run on the binder thread. All we've got to do is
3555 * call the real BpGraphicBufferProducer.
3556 */
3557 virtual void handleMessage(const Message& message) {
3558 int what = message.what;
3559 // Prevent reads below from happening before the read from Message
3560 atomic_thread_fence(memory_order_acquire);
3561 if (what == MSG_API_CALL) {
3562 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
3563 barrier.open();
3564 } else if (what == MSG_EXIT) {
3565 exitRequested = true;
3566 }
3567 }
3568
3569public:
3570 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3571 : impl(impl),
3572 looper(new Looper(true)),
3573 result(NO_ERROR),
3574 exitPending(false),
3575 exitRequested(false),
3576 code(0),
3577 data(NULL),
3578 reply(NULL)
3579 {}
3580
3581 // Binder thread
3582 status_t waitForResponse() {
3583 do {
3584 looper->pollOnce(-1);
3585 } while (!exitRequested);
3586 return result;
3587 }
3588
3589 // Client thread
3590 void exit(status_t result) {
3591 this->result = result;
3592 exitPending = true;
3593 // Ensure this->result is visible to the binder thread before it
3594 // handles the message.
3595 atomic_thread_fence(memory_order_release);
3596 looper->sendMessage(this, Message(MSG_EXIT));
3597 }
3598};
3599
3600
3601status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3602 const sp<IGraphicBufferProducer>& producer,
3603 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003604 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003605 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
3606
3607 if (CC_UNLIKELY(display == 0))
3608 return BAD_VALUE;
3609
3610 if (CC_UNLIKELY(producer == 0))
3611 return BAD_VALUE;
3612
3613 // if we have secure windows on this display, never allow the screen capture
3614 // unless the producer interface is local (i.e.: we can take a screenshot for
3615 // ourselves).
3616 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
3617
3618 // Convert to surfaceflinger's internal rotation type.
3619 Transform::orientation_flags rotationFlags;
3620 switch (rotation) {
3621 case ISurfaceComposer::eRotateNone:
3622 rotationFlags = Transform::ROT_0;
3623 break;
3624 case ISurfaceComposer::eRotate90:
3625 rotationFlags = Transform::ROT_90;
3626 break;
3627 case ISurfaceComposer::eRotate180:
3628 rotationFlags = Transform::ROT_180;
3629 break;
3630 case ISurfaceComposer::eRotate270:
3631 rotationFlags = Transform::ROT_270;
3632 break;
3633 default:
3634 rotationFlags = Transform::ROT_0;
3635 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3636 break;
3637 }
3638
3639 class MessageCaptureScreen : public MessageBase {
3640 SurfaceFlinger* flinger;
3641 sp<IBinder> display;
3642 sp<IGraphicBufferProducer> producer;
3643 Rect sourceCrop;
3644 uint32_t reqWidth, reqHeight;
Robert Carrae060832016-11-28 10:51:00 -08003645 int32_t minLayerZ,maxLayerZ;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003646 bool useIdentityTransform;
3647 Transform::orientation_flags rotation;
3648 status_t result;
3649 bool isLocalScreenshot;
3650 public:
3651 MessageCaptureScreen(SurfaceFlinger* flinger,
3652 const sp<IBinder>& display,
3653 const sp<IGraphicBufferProducer>& producer,
3654 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003655 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003656 bool useIdentityTransform,
3657 Transform::orientation_flags rotation,
3658 bool isLocalScreenshot)
3659 : flinger(flinger), display(display), producer(producer),
3660 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
3661 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
3662 useIdentityTransform(useIdentityTransform),
3663 rotation(rotation), result(PERMISSION_DENIED),
3664 isLocalScreenshot(isLocalScreenshot)
3665 {
3666 }
3667 status_t getResult() const {
3668 return result;
3669 }
3670 virtual bool handler() {
3671 Mutex::Autolock _l(flinger->mStateLock);
3672 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
3673 result = flinger->captureScreenImplLocked(hw, producer,
3674 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3675 useIdentityTransform, rotation, isLocalScreenshot);
3676 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
3677 return true;
3678 }
3679 };
3680
3681 // this creates a "fake" BBinder which will serve as a "fake" remote
3682 // binder to receive the marshaled calls and forward them to the
3683 // real remote (a BpGraphicBufferProducer)
3684 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3685
3686 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3687 // which does the marshaling work forwards to our "fake remote" above.
3688 sp<MessageBase> msg = new MessageCaptureScreen(this,
3689 display, IGraphicBufferProducer::asInterface( wrapper ),
3690 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3691 useIdentityTransform, rotationFlags, isLocalScreenshot);
3692
3693 status_t res = postMessageAsync(msg);
3694 if (res == NO_ERROR) {
3695 res = wrapper->waitForResponse();
3696 }
3697 return res;
3698}
3699
3700
3701void SurfaceFlinger::renderScreenImplLocked(
3702 const sp<const DisplayDevice>& hw,
3703 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003704 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003705 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
3706{
3707 ATRACE_CALL();
3708 RenderEngine& engine(getRenderEngine());
3709
3710 // get screen geometry
3711 const int32_t hw_w = hw->getWidth();
3712 const int32_t hw_h = hw->getHeight();
3713 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
3714 static_cast<int32_t>(reqHeight) != hw_h;
3715
3716 // if a default or invalid sourceCrop is passed in, set reasonable values
3717 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3718 !sourceCrop.isValid()) {
3719 sourceCrop.setLeftTop(Point(0, 0));
3720 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3721 }
3722
3723 // ensure that sourceCrop is inside screen
3724 if (sourceCrop.left < 0) {
3725 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3726 }
3727 if (sourceCrop.right > hw_w) {
3728 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
3729 }
3730 if (sourceCrop.top < 0) {
3731 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3732 }
3733 if (sourceCrop.bottom > hw_h) {
3734 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
3735 }
3736
3737 // make sure to clear all GL error flags
3738 engine.checkErrors();
3739
3740 // set-up our viewport
3741 engine.setViewportAndProjection(
3742 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
3743 engine.disableTexturing();
3744
3745 // redraw the screen entirely...
3746 engine.clearWithColor(0, 0, 0, 1);
3747
Robert Carr1f0a16a2016-10-24 16:27:39 -07003748 // We loop through the first level of layers without traversing,
3749 // as we need to interpret min/max layer Z in the top level Z space.
3750 for (const auto& layer : mDrawingState.layersSortedByZ) {
3751 if (layer->getLayerStack() != hw->getLayerStack()) {
3752 continue;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003753 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003754 const Layer::State& state(layer->getDrawingState());
3755 if (state.z < minLayerZ || state.z > maxLayerZ) {
3756 continue;
3757 }
3758 layer->traverseInZOrder([&](Layer* layer) {
3759 if (!layer->isVisible()) {
3760 return;
3761 }
3762 if (filtering) layer->setFiltering(true);
3763 layer->draw(hw, useIdentityTransform);
3764 if (filtering) layer->setFiltering(false);
3765 });
3766 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003767
3768 // compositionComplete is needed for older driver
3769 hw->compositionComplete();
3770 hw->setViewportAndProjection();
3771}
3772
3773
3774status_t SurfaceFlinger::captureScreenImplLocked(
3775 const sp<const DisplayDevice>& hw,
3776 const sp<IGraphicBufferProducer>& producer,
3777 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003778 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003779 bool useIdentityTransform, Transform::orientation_flags rotation,
3780 bool isLocalScreenshot)
3781{
3782 ATRACE_CALL();
3783
3784 // get screen geometry
3785 uint32_t hw_w = hw->getWidth();
3786 uint32_t hw_h = hw->getHeight();
3787
3788 if (rotation & Transform::ROT_90) {
3789 std::swap(hw_w, hw_h);
3790 }
3791
3792 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3793 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3794 reqWidth, reqHeight, hw_w, hw_h);
3795 return BAD_VALUE;
3796 }
3797
3798 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3799 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3800
3801 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07003802 for (const auto& layer : mDrawingState.layersSortedByZ) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003803 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07003804 if ((layer->getLayerStack() != hw->getLayerStack()) ||
3805 (state.z < minLayerZ || state.z > maxLayerZ)) {
3806 continue;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003807 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003808 layer->traverseInZOrder([&](Layer *layer) {
3809 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
3810 layer->isSecure());
3811 });
3812 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003813
3814 if (!isLocalScreenshot && secureLayerIsVisible) {
3815 ALOGW("FB is protected: PERMISSION_DENIED");
3816 return PERMISSION_DENIED;
3817 }
3818
3819 // create a surface (because we're a producer, and we need to
3820 // dequeue/queue a buffer)
3821 sp<Surface> sur = new Surface(producer, false);
3822 ANativeWindow* window = sur.get();
3823
3824 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3825 if (result == NO_ERROR) {
3826 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3827 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
3828
3829 int err = 0;
3830 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
3831 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
3832 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3833 err |= native_window_set_usage(window, usage);
3834
3835 if (err == NO_ERROR) {
3836 ANativeWindowBuffer* buffer;
3837 /* TODO: Once we have the sync framework everywhere this can use
3838 * server-side waits on the fence that dequeueBuffer returns.
3839 */
3840 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3841 if (result == NO_ERROR) {
3842 int syncFd = -1;
3843 // create an EGLImage from the buffer so we can later
3844 // turn it into a texture
3845 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3846 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3847 if (image != EGL_NO_IMAGE_KHR) {
3848 // this binds the given EGLImage as a framebuffer for the
3849 // duration of this scope.
3850 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3851 if (imageBond.getStatus() == NO_ERROR) {
3852 // this will in fact render into our dequeued buffer
3853 // via an FBO, which means we didn't have to create
3854 // an EGLSurface and therefore we're not
3855 // dependent on the context's EGLConfig.
3856 renderScreenImplLocked(
3857 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3858 useIdentityTransform, rotation);
3859
3860 // Attempt to create a sync khr object that can produce a sync point. If that
3861 // isn't available, create a non-dupable sync object in the fallback path and
3862 // wait on it directly.
3863 EGLSyncKHR sync;
3864 if (!DEBUG_SCREENSHOTS) {
3865 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
3866 // native fence fd will not be populated until flush() is done.
3867 getRenderEngine().flush();
3868 } else {
3869 sync = EGL_NO_SYNC_KHR;
3870 }
3871 if (sync != EGL_NO_SYNC_KHR) {
3872 // get the sync fd
3873 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3874 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3875 ALOGW("captureScreen: failed to dup sync khr object");
3876 syncFd = -1;
3877 }
3878 eglDestroySyncKHR(mEGLDisplay, sync);
3879 } else {
3880 // fallback path
3881 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3882 if (sync != EGL_NO_SYNC_KHR) {
3883 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3884 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3885 EGLint eglErr = eglGetError();
3886 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3887 ALOGW("captureScreen: fence wait timed out");
3888 } else {
3889 ALOGW_IF(eglErr != EGL_SUCCESS,
3890 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3891 }
3892 eglDestroySyncKHR(mEGLDisplay, sync);
3893 } else {
3894 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3895 }
3896 }
3897 if (DEBUG_SCREENSHOTS) {
3898 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3899 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3900 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3901 hw, minLayerZ, maxLayerZ);
3902 delete [] pixels;
3903 }
3904
3905 } else {
3906 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3907 result = INVALID_OPERATION;
3908 window->cancelBuffer(window, buffer, syncFd);
3909 buffer = NULL;
3910 }
3911 // destroy our image
3912 eglDestroyImageKHR(mEGLDisplay, image);
3913 } else {
3914 result = BAD_VALUE;
3915 }
3916 if (buffer) {
3917 // queueBuffer takes ownership of syncFd
3918 result = window->queueBuffer(window, buffer, syncFd);
3919 }
3920 }
3921 } else {
3922 result = BAD_VALUE;
3923 }
3924 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3925 }
3926
3927 return result;
3928}
3929
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003930void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08003931 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003932 if (DEBUG_SCREENSHOTS) {
3933 for (size_t y=0 ; y<h ; y++) {
3934 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3935 for (size_t x=0 ; x<w ; x++) {
3936 if (p[x] != 0xFF000000) return;
3937 }
3938 }
3939 ALOGE("*** we just took a black screenshot ***\n"
3940 "requested minz=%d, maxz=%d, layerStack=%d",
3941 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr2047fae2016-11-28 14:09:09 -08003942 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07003943 for (const auto& layer : mDrawingState.layersSortedByZ) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003944 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07003945 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
3946 state.z <= maxLayerZ) {
3947 layer->traverseInZOrder([&](Layer* layer) {
3948 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x",
3949 layer->isVisible() ? '+' : '-',
3950 i, layer->getName().string(), layer->getLayerStack(), state.z,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003951 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003952 i++;
3953 });
3954 }
3955 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003956 }
3957}
3958
3959// ---------------------------------------------------------------------------
3960
Robert Carr2047fae2016-11-28 14:09:09 -08003961void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
3962 layersSortedByZ.traverseInZOrder(consume);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003963}
3964
Robert Carr2047fae2016-11-28 14:09:09 -08003965void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
3966 layersSortedByZ.traverseInReverseZOrder(consume);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003967}
3968
3969}; // namespace android
3970
3971
3972#if defined(__gl_h_)
3973#error "don't include gl/gl.h in this file"
3974#endif
3975
3976#if defined(__gl2_h_)
3977#error "don't include gl2/gl2.h in this file"
3978#endif