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