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