blob: de46dfa0ffac1b880764c1f7e7c82f3f73e32cf4 [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) {
910 case MessageQueue::TRANSACTION: {
911 handleMessageTransaction();
912 break;
913 }
914 case MessageQueue::INVALIDATE: {
915 bool refreshNeeded = handleMessageTransaction();
916 refreshNeeded |= handleMessageInvalidate();
917 refreshNeeded |= mRepaintEverything;
918 if (refreshNeeded) {
919 // Signal a refresh if a transaction modified the window state,
920 // a new buffer was latched, or if HWC has requested a full
921 // repaint
922 signalRefresh();
923 }
924 break;
925 }
926 case MessageQueue::REFRESH: {
927 handleMessageRefresh();
928 break;
929 }
930 }
931}
932
933bool SurfaceFlinger::handleMessageTransaction() {
934 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
935 if (transactionFlags) {
936 handleTransaction(transactionFlags);
937 return true;
938 }
939 return false;
940}
941
942bool SurfaceFlinger::handleMessageInvalidate() {
943 ATRACE_CALL();
944 return handlePageFlip();
945}
946
947void SurfaceFlinger::handleMessageRefresh() {
948 ATRACE_CALL();
949
Pablo Ceballos69a1a382016-03-30 15:28:05 -0700950#ifdef ENABLE_FENCE_TRACKING
Pablo Ceballos40845df2016-01-25 17:41:15 -0800951 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Pablo Ceballos69a1a382016-03-30 15:28:05 -0700952#else
953 nsecs_t refreshStartTime = 0;
954#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -0800955 static nsecs_t previousExpectedPresent = 0;
956 nsecs_t expectedPresent = mPrimaryDispSync.computeNextRefresh(0);
957 static bool previousFrameMissed = false;
958 bool frameMissed = (expectedPresent == previousExpectedPresent);
959 if (frameMissed != previousFrameMissed) {
960 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
961 }
962 previousFrameMissed = frameMissed;
963
964 if (CC_UNLIKELY(mDropMissedFrames && frameMissed)) {
965 // Latch buffers, but don't send anything to HWC, then signal another
966 // wakeup for the next vsync
967 preComposition();
968 repaintEverything();
969 } else {
970 preComposition();
971 rebuildLayerStacks();
972 setUpHWComposer();
973 doDebugFlashRegions();
974 doComposition();
Pablo Ceballos40845df2016-01-25 17:41:15 -0800975 postComposition(refreshStartTime);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800976 }
977
978 previousExpectedPresent = mPrimaryDispSync.computeNextRefresh(0);
979}
980
981void SurfaceFlinger::doDebugFlashRegions()
982{
983 // is debugging enabled
984 if (CC_LIKELY(!mDebugRegion))
985 return;
986
987 const bool repaintEverything = mRepaintEverything;
988 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
989 const sp<DisplayDevice>& hw(mDisplays[dpy]);
990 if (hw->isDisplayOn()) {
991 // transform the dirty region into this screen's coordinate space
992 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
993 if (!dirtyRegion.isEmpty()) {
994 // redraw the whole screen
995 doComposeSurfaces(hw, Region(hw->bounds()));
996
997 // and draw the dirty region
998 const int32_t height = hw->getHeight();
999 RenderEngine& engine(getRenderEngine());
1000 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1001
1002 hw->compositionComplete();
1003 hw->swapBuffers(getHwComposer());
1004 }
1005 }
1006 }
1007
1008 postFramebuffer();
1009
1010 if (mDebugRegion > 1) {
1011 usleep(mDebugRegion * 1000);
1012 }
1013
1014 HWComposer& hwc(getHwComposer());
1015 if (hwc.initCheck() == NO_ERROR) {
1016 status_t err = hwc.prepare();
1017 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1018 }
1019}
1020
1021void SurfaceFlinger::preComposition()
1022{
1023 bool needExtraInvalidate = false;
1024 const LayerVector& layers(mDrawingState.layersSortedByZ);
1025 const size_t count = layers.size();
1026 for (size_t i=0 ; i<count ; i++) {
1027 if (layers[i]->onPreComposition()) {
1028 needExtraInvalidate = true;
1029 }
1030 }
1031 if (needExtraInvalidate) {
1032 signalLayerUpdate();
1033 }
1034}
1035
Pablo Ceballos69a1a382016-03-30 15:28:05 -07001036#ifdef ENABLE_FENCE_TRACKING
Pablo Ceballos40845df2016-01-25 17:41:15 -08001037void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Pablo Ceballos69a1a382016-03-30 15:28:05 -07001038#else
1039void SurfaceFlinger::postComposition(nsecs_t /*refreshStartTime*/)
1040#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001041{
1042 const LayerVector& layers(mDrawingState.layersSortedByZ);
1043 const size_t count = layers.size();
1044 for (size_t i=0 ; i<count ; i++) {
1045 layers[i]->onPostComposition();
1046 }
1047
1048 const HWComposer& hwc = getHwComposer();
1049 sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
1050
1051 if (presentFence->isValid()) {
1052 if (mPrimaryDispSync.addPresentFence(presentFence)) {
1053 enableHardwareVsync();
1054 } else {
1055 disableHardwareVsync(false);
1056 }
1057 }
1058
1059 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
1060 if (kIgnorePresentFences) {
1061 if (hw->isDisplayOn()) {
1062 enableHardwareVsync();
1063 }
1064 }
1065
Pablo Ceballos69a1a382016-03-30 15:28:05 -07001066#ifdef ENABLE_FENCE_TRACKING
Pablo Ceballos40845df2016-01-25 17:41:15 -08001067 mFenceTracker.addFrame(refreshStartTime, presentFence,
1068 hw->getVisibleLayersSortedByZ(), hw->getClientTargetAcquireFence());
Pablo Ceballos69a1a382016-03-30 15:28:05 -07001069#endif
Pablo Ceballos40845df2016-01-25 17:41:15 -08001070
Dan Stoza9e56aa02015-11-02 13:00:03 -08001071 if (mAnimCompositionPending) {
1072 mAnimCompositionPending = false;
1073
1074 if (presentFence->isValid()) {
1075 mAnimFrameTracker.setActualPresentFence(presentFence);
1076 } else {
1077 // The HWC doesn't support present fences, so use the refresh
1078 // timestamp instead.
1079 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
1080 mAnimFrameTracker.setActualPresentTime(presentTime);
1081 }
1082 mAnimFrameTracker.advanceFrame();
1083 }
1084
1085 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1086 return;
1087 }
1088
1089 nsecs_t currentTime = systemTime();
1090 if (mHasPoweredOff) {
1091 mHasPoweredOff = false;
1092 } else {
1093 nsecs_t period = mPrimaryDispSync.getPeriod();
1094 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1095 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1096 if (numPeriods < NUM_BUCKETS - 1) {
1097 mFrameBuckets[numPeriods] += elapsedTime;
1098 } else {
1099 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1100 }
1101 mTotalTime += elapsedTime;
1102 }
1103 mLastSwapTime = currentTime;
1104}
1105
1106void SurfaceFlinger::rebuildLayerStacks() {
1107 // rebuild the visible layer list per screen
1108 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1109 ATRACE_CALL();
1110 mVisibleRegionsDirty = false;
1111 invalidateHwcGeometry();
1112
1113 const LayerVector& layers(mDrawingState.layersSortedByZ);
1114 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1115 Region opaqueRegion;
1116 Region dirtyRegion;
1117 Vector< sp<Layer> > layersSortedByZ;
1118 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1119 const Transform& tr(hw->getTransform());
1120 const Rect bounds(hw->getBounds());
1121 if (hw->isDisplayOn()) {
1122 SurfaceFlinger::computeVisibleRegions(layers,
1123 hw->getLayerStack(), dirtyRegion, opaqueRegion);
1124
1125 const size_t count = layers.size();
1126 for (size_t i=0 ; i<count ; i++) {
1127 const sp<Layer>& layer(layers[i]);
1128 const Layer::State& s(layer->getDrawingState());
1129 if (s.layerStack == hw->getLayerStack()) {
1130 Region drawRegion(tr.transform(
1131 layer->visibleNonTransparentRegion));
1132 drawRegion.andSelf(bounds);
1133 if (!drawRegion.isEmpty()) {
1134 layersSortedByZ.add(layer);
1135 }
1136 }
1137 }
1138 }
1139 hw->setVisibleLayersSortedByZ(layersSortedByZ);
1140 hw->undefinedRegion.set(bounds);
1141 hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1142 hw->dirtyRegion.orSelf(dirtyRegion);
1143 }
1144 }
1145}
1146
1147void SurfaceFlinger::setUpHWComposer() {
1148 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1149 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1150 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1151 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1152
1153 // If nothing has changed (!dirty), don't recompose.
1154 // If something changed, but we don't currently have any visible layers,
1155 // and didn't when we last did a composition, then skip it this time.
1156 // The second rule does two things:
1157 // - When all layers are removed from a display, we'll emit one black
1158 // frame, then nothing more until we get new layers.
1159 // - When a display is created with a private layer stack, we won't
1160 // emit any black frames until a layer is added to the layer stack.
1161 bool mustRecompose = dirty && !(empty && wasEmpty);
1162
1163 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1164 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1165 mustRecompose ? "doing" : "skipping",
1166 dirty ? "+" : "-",
1167 empty ? "+" : "-",
1168 wasEmpty ? "+" : "-");
1169
1170 mDisplays[dpy]->beginFrame(mustRecompose);
1171
1172 if (mustRecompose) {
1173 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1174 }
1175 }
1176
1177 HWComposer& hwc(getHwComposer());
1178 if (hwc.initCheck() == NO_ERROR) {
1179 // build the h/w work list
1180 if (CC_UNLIKELY(mHwWorkListDirty)) {
1181 mHwWorkListDirty = false;
1182 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1183 sp<const DisplayDevice> hw(mDisplays[dpy]);
1184 const int32_t id = hw->getHwcDisplayId();
1185 if (id >= 0) {
1186 const Vector< sp<Layer> >& currentLayers(
1187 hw->getVisibleLayersSortedByZ());
1188 const size_t count = currentLayers.size();
1189 if (hwc.createWorkList(id, count) == NO_ERROR) {
1190 HWComposer::LayerListIterator cur = hwc.begin(id);
1191 const HWComposer::LayerListIterator end = hwc.end(id);
1192 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1193 const sp<Layer>& layer(currentLayers[i]);
1194 layer->setGeometry(hw, *cur);
1195 if (mDebugDisableHWC || mDebugRegion || mDaltonize || mHasColorMatrix) {
1196 cur->setSkip(true);
1197 }
1198 }
1199 }
1200 }
1201 }
1202 }
1203
1204 // set the per-frame data
1205 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1206 sp<const DisplayDevice> hw(mDisplays[dpy]);
1207 const int32_t id = hw->getHwcDisplayId();
1208 if (id >= 0) {
1209 const Vector< sp<Layer> >& currentLayers(
1210 hw->getVisibleLayersSortedByZ());
1211 const size_t count = currentLayers.size();
1212 HWComposer::LayerListIterator cur = hwc.begin(id);
1213 const HWComposer::LayerListIterator end = hwc.end(id);
1214 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1215 /*
1216 * update the per-frame h/w composer data for each layer
1217 * and build the transparent region of the FB
1218 */
1219 const sp<Layer>& layer(currentLayers[i]);
1220 layer->setPerFrameData(hw, *cur);
1221 }
1222 }
1223 }
1224
1225 // If possible, attempt to use the cursor overlay on each display.
1226 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1227 sp<const DisplayDevice> hw(mDisplays[dpy]);
1228 const int32_t id = hw->getHwcDisplayId();
1229 if (id >= 0) {
1230 const Vector< sp<Layer> >& currentLayers(
1231 hw->getVisibleLayersSortedByZ());
1232 const size_t count = currentLayers.size();
1233 HWComposer::LayerListIterator cur = hwc.begin(id);
1234 const HWComposer::LayerListIterator end = hwc.end(id);
1235 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1236 const sp<Layer>& layer(currentLayers[i]);
1237 if (layer->isPotentialCursor()) {
1238 cur->setIsCursorLayerHint();
1239 break;
1240 }
1241 }
1242 }
1243 }
1244
1245 status_t err = hwc.prepare();
1246 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1247
1248 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1249 sp<const DisplayDevice> hw(mDisplays[dpy]);
1250 hw->prepareFrame(hwc);
1251 }
1252 }
1253}
1254
1255void SurfaceFlinger::doComposition() {
1256 ATRACE_CALL();
1257 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
1258 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1259 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1260 if (hw->isDisplayOn()) {
1261 // transform the dirty region into this screen's coordinate space
1262 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1263
1264 // repaint the framebuffer (if needed)
1265 doDisplayComposition(hw, dirtyRegion);
1266
1267 hw->dirtyRegion.clear();
1268 hw->flip(hw->swapRegion);
1269 hw->swapRegion.clear();
1270 }
1271 // inform the h/w that we're done compositing
1272 hw->compositionComplete();
1273 }
1274 postFramebuffer();
1275}
1276
1277void SurfaceFlinger::postFramebuffer()
1278{
1279 ATRACE_CALL();
1280
1281 const nsecs_t now = systemTime();
1282 mDebugInSwapBuffers = now;
1283
1284 HWComposer& hwc(getHwComposer());
1285 if (hwc.initCheck() == NO_ERROR) {
1286 if (!hwc.supportsFramebufferTarget()) {
1287 // EGL spec says:
1288 // "surface must be bound to the calling thread's current context,
1289 // for the current rendering API."
1290 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1291 }
1292 hwc.commit();
1293 }
1294
1295 // make the default display current because the VirtualDisplayDevice code cannot
1296 // deal with dequeueBuffer() being called outside of the composition loop; however
1297 // the code below can call glFlush() which is allowed (and does in some case) call
1298 // dequeueBuffer().
1299 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1300
1301 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1302 sp<const DisplayDevice> hw(mDisplays[dpy]);
1303 const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ());
1304 hw->onSwapBuffersCompleted(hwc);
1305 const size_t count = currentLayers.size();
1306 int32_t id = hw->getHwcDisplayId();
1307 if (id >=0 && hwc.initCheck() == NO_ERROR) {
1308 HWComposer::LayerListIterator cur = hwc.begin(id);
1309 const HWComposer::LayerListIterator end = hwc.end(id);
1310 for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
1311 currentLayers[i]->onLayerDisplayed(hw, &*cur);
1312 }
1313 } else {
1314 for (size_t i = 0; i < count; i++) {
1315 currentLayers[i]->onLayerDisplayed(hw, NULL);
1316 }
1317 }
1318 }
1319
1320 mLastSwapBufferTime = systemTime() - now;
1321 mDebugInSwapBuffers = 0;
1322
1323 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1324 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1325 logFrameStats();
1326 }
1327}
1328
1329void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
1330{
1331 ATRACE_CALL();
1332
1333 // here we keep a copy of the drawing state (that is the state that's
1334 // going to be overwritten by handleTransactionLocked()) outside of
1335 // mStateLock so that the side-effects of the State assignment
1336 // don't happen with mStateLock held (which can cause deadlocks).
1337 State drawingState(mDrawingState);
1338
1339 Mutex::Autolock _l(mStateLock);
1340 const nsecs_t now = systemTime();
1341 mDebugInTransaction = now;
1342
1343 // Here we're guaranteed that some transaction flags are set
1344 // so we can call handleTransactionLocked() unconditionally.
1345 // We call getTransactionFlags(), which will also clear the flags,
1346 // with mStateLock held to guarantee that mCurrentState won't change
1347 // until the transaction is committed.
1348
1349 transactionFlags = getTransactionFlags(eTransactionMask);
1350 handleTransactionLocked(transactionFlags);
1351
1352 mLastTransactionTime = systemTime() - now;
1353 mDebugInTransaction = 0;
1354 invalidateHwcGeometry();
1355 // here the transaction has been committed
1356}
1357
1358void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
1359{
1360 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
1361 const size_t count = currentLayers.size();
1362
1363 // Notify all layers of available frames
1364 for (size_t i = 0; i < count; ++i) {
1365 currentLayers[i]->notifyAvailableFrames();
1366 }
1367
1368 /*
1369 * Traversal of the children
1370 * (perform the transaction for each of them if needed)
1371 */
1372
1373 if (transactionFlags & eTraversalNeeded) {
1374 for (size_t i=0 ; i<count ; i++) {
1375 const sp<Layer>& layer(currentLayers[i]);
1376 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1377 if (!trFlags) continue;
1378
1379 const uint32_t flags = layer->doTransaction(0);
1380 if (flags & Layer::eVisibleRegion)
1381 mVisibleRegionsDirty = true;
1382 }
1383 }
1384
1385 /*
1386 * Perform display own transactions if needed
1387 */
1388
1389 if (transactionFlags & eDisplayTransactionNeeded) {
1390 // here we take advantage of Vector's copy-on-write semantics to
1391 // improve performance by skipping the transaction entirely when
1392 // know that the lists are identical
1393 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1394 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
1395 if (!curr.isIdenticalTo(draw)) {
1396 mVisibleRegionsDirty = true;
1397 const size_t cc = curr.size();
1398 size_t dc = draw.size();
1399
1400 // find the displays that were removed
1401 // (ie: in drawing state but not in current state)
1402 // also handle displays that changed
1403 // (ie: displays that are in both lists)
1404 for (size_t i=0 ; i<dc ; i++) {
1405 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1406 if (j < 0) {
1407 // in drawing state but not in current state
1408 if (!draw[i].isMainDisplay()) {
1409 // Call makeCurrent() on the primary display so we can
1410 // be sure that nothing associated with this display
1411 // is current.
1412 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
1413 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
1414 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1415 if (hw != NULL)
1416 hw->disconnect(getHwComposer());
1417 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
1418 mEventThread->onHotplugReceived(draw[i].type, false);
1419 mDisplays.removeItem(draw.keyAt(i));
1420 } else {
1421 ALOGW("trying to remove the main display");
1422 }
1423 } else {
1424 // this display is in both lists. see if something changed.
1425 const DisplayDeviceState& state(curr[j]);
1426 const wp<IBinder>& display(curr.keyAt(j));
1427 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1428 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
1429 if (state_binder != draw_binder) {
1430 // changing the surface is like destroying and
1431 // recreating the DisplayDevice, so we just remove it
1432 // from the drawing state, so that it get re-added
1433 // below.
1434 sp<DisplayDevice> hw(getDisplayDevice(display));
1435 if (hw != NULL)
1436 hw->disconnect(getHwComposer());
1437 mDisplays.removeItem(display);
1438 mDrawingState.displays.removeItemsAt(i);
1439 dc--; i--;
1440 // at this point we must loop to the next item
1441 continue;
1442 }
1443
1444 const sp<DisplayDevice> disp(getDisplayDevice(display));
1445 if (disp != NULL) {
1446 if (state.layerStack != draw[i].layerStack) {
1447 disp->setLayerStack(state.layerStack);
1448 }
1449 if ((state.orientation != draw[i].orientation)
1450 || (state.viewport != draw[i].viewport)
1451 || (state.frame != draw[i].frame))
1452 {
1453 disp->setProjection(state.orientation,
1454 state.viewport, state.frame);
1455 }
1456 if (state.width != draw[i].width || state.height != draw[i].height) {
1457 disp->setDisplaySize(state.width, state.height);
1458 }
1459 }
1460 }
1461 }
1462
1463 // find displays that were added
1464 // (ie: in current state but not in drawing state)
1465 for (size_t i=0 ; i<cc ; i++) {
1466 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
1467 const DisplayDeviceState& state(curr[i]);
1468
1469 sp<DisplaySurface> dispSurface;
1470 sp<IGraphicBufferProducer> producer;
1471 sp<IGraphicBufferProducer> bqProducer;
1472 sp<IGraphicBufferConsumer> bqConsumer;
1473 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1474 new GraphicBufferAlloc());
1475
1476 int32_t hwcDisplayId = -1;
1477 if (state.isVirtualDisplay()) {
1478 // Virtual displays without a surface are dormant:
1479 // they have external state (layer stack, projection,
1480 // etc.) but no internal state (i.e. a DisplayDevice).
1481 if (state.surface != NULL) {
1482
1483 int width = 0;
1484 int status = state.surface->query(
1485 NATIVE_WINDOW_WIDTH, &width);
1486 ALOGE_IF(status != NO_ERROR,
1487 "Unable to query width (%d)", status);
1488 int height = 0;
1489 status = state.surface->query(
1490 NATIVE_WINDOW_HEIGHT, &height);
1491 ALOGE_IF(status != NO_ERROR,
1492 "Unable to query height (%d)", status);
1493 if (MAX_VIRTUAL_DISPLAY_DIMENSION == 0 ||
1494 (width <= MAX_VIRTUAL_DISPLAY_DIMENSION &&
1495 height <= MAX_VIRTUAL_DISPLAY_DIMENSION)) {
1496 hwcDisplayId = allocateHwcDisplayId(state.type);
1497 }
1498
1499 sp<VirtualDisplaySurface> vds = new VirtualDisplaySurface(
1500 *mHwc, hwcDisplayId, state.surface,
1501 bqProducer, bqConsumer, state.displayName);
1502
1503 dispSurface = vds;
1504 producer = vds;
1505 }
1506 } else {
1507 ALOGE_IF(state.surface!=NULL,
1508 "adding a supported display, but rendering "
1509 "surface is provided (%p), ignoring it",
1510 state.surface.get());
1511 hwcDisplayId = allocateHwcDisplayId(state.type);
1512 // for supported (by hwc) displays we provide our
1513 // own rendering surface
1514 dispSurface = new FramebufferSurface(*mHwc, state.type,
1515 bqConsumer);
1516 producer = bqProducer;
1517 }
1518
1519 const wp<IBinder>& display(curr.keyAt(i));
1520 if (dispSurface != NULL) {
1521 sp<DisplayDevice> hw = new DisplayDevice(this,
1522 state.type, hwcDisplayId,
1523 mHwc->getFormat(hwcDisplayId), state.isSecure,
1524 display, dispSurface, producer,
1525 mRenderEngine->getEGLConfig());
1526 hw->setLayerStack(state.layerStack);
1527 hw->setProjection(state.orientation,
1528 state.viewport, state.frame);
1529 hw->setDisplayName(state.displayName);
1530 mDisplays.add(display, hw);
1531 if (state.isVirtualDisplay()) {
1532 if (hwcDisplayId >= 0) {
1533 mHwc->setVirtualDisplayProperties(hwcDisplayId,
1534 hw->getWidth(), hw->getHeight(),
1535 hw->getFormat());
1536 }
1537 } else {
1538 mEventThread->onHotplugReceived(state.type, true);
1539 }
1540 }
1541 }
1542 }
1543 }
1544 }
1545
1546 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1547 // The transform hint might have changed for some layers
1548 // (either because a display has changed, or because a layer
1549 // as changed).
1550 //
1551 // Walk through all the layers in currentLayers,
1552 // and update their transform hint.
1553 //
1554 // If a layer is visible only on a single display, then that
1555 // display is used to calculate the hint, otherwise we use the
1556 // default display.
1557 //
1558 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1559 // the hint is set before we acquire a buffer from the surface texture.
1560 //
1561 // NOTE: layer transactions have taken place already, so we use their
1562 // drawing state. However, SurfaceFlinger's own transaction has not
1563 // happened yet, so we must use the current state layer list
1564 // (soon to become the drawing state list).
1565 //
1566 sp<const DisplayDevice> disp;
1567 uint32_t currentlayerStack = 0;
1568 for (size_t i=0; i<count; i++) {
1569 // NOTE: we rely on the fact that layers are sorted by
1570 // layerStack first (so we don't have to traverse the list
1571 // of displays for every layer).
1572 const sp<Layer>& layer(currentLayers[i]);
1573 uint32_t layerStack = layer->getDrawingState().layerStack;
1574 if (i==0 || currentlayerStack != layerStack) {
1575 currentlayerStack = layerStack;
1576 // figure out if this layerstack is mirrored
1577 // (more than one display) if so, pick the default display,
1578 // if not, pick the only display it's on.
1579 disp.clear();
1580 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1581 sp<const DisplayDevice> hw(mDisplays[dpy]);
1582 if (hw->getLayerStack() == currentlayerStack) {
1583 if (disp == NULL) {
1584 disp = hw;
1585 } else {
1586 disp = NULL;
1587 break;
1588 }
1589 }
1590 }
1591 }
1592 if (disp == NULL) {
1593 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1594 // redraw after transform hint changes. See bug 8508397.
1595
1596 // could be null when this layer is using a layerStack
1597 // that is not visible on any display. Also can occur at
1598 // screen off/on times.
1599 disp = getDefaultDisplayDevice();
1600 }
1601 layer->updateTransformHint(disp);
1602 }
1603 }
1604
1605
1606 /*
1607 * Perform our own transaction if needed
1608 */
1609
1610 const LayerVector& layers(mDrawingState.layersSortedByZ);
1611 if (currentLayers.size() > layers.size()) {
1612 // layers have been added
1613 mVisibleRegionsDirty = true;
1614 }
1615
1616 // some layers might have been removed, so
1617 // we need to update the regions they're exposing.
1618 if (mLayersRemoved) {
1619 mLayersRemoved = false;
1620 mVisibleRegionsDirty = true;
1621 const size_t count = layers.size();
1622 for (size_t i=0 ; i<count ; i++) {
1623 const sp<Layer>& layer(layers[i]);
1624 if (currentLayers.indexOf(layer) < 0) {
1625 // this layer is not visible anymore
1626 // TODO: we could traverse the tree from front to back and
1627 // compute the actual visible region
1628 // TODO: we could cache the transformed region
1629 const Layer::State& s(layer->getDrawingState());
Robert Carr3dcabfa2016-03-01 18:36:58 -08001630 Region visibleReg = s.active.transform.transform(
Dan Stoza9e56aa02015-11-02 13:00:03 -08001631 Region(Rect(s.active.w, s.active.h)));
1632 invalidateLayerStack(s.layerStack, visibleReg);
1633 }
1634 }
1635 }
1636
1637 commitTransaction();
1638
1639 updateCursorAsync();
1640}
1641
1642void SurfaceFlinger::updateCursorAsync()
1643{
1644 HWComposer& hwc(getHwComposer());
1645 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1646 sp<const DisplayDevice> hw(mDisplays[dpy]);
1647 const int32_t id = hw->getHwcDisplayId();
1648 if (id < 0) {
1649 continue;
1650 }
1651 const Vector< sp<Layer> >& currentLayers(
1652 hw->getVisibleLayersSortedByZ());
1653 const size_t count = currentLayers.size();
1654 HWComposer::LayerListIterator cur = hwc.begin(id);
1655 const HWComposer::LayerListIterator end = hwc.end(id);
1656 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1657 if (cur->getCompositionType() != HWC_CURSOR_OVERLAY) {
1658 continue;
1659 }
1660 const sp<Layer>& layer(currentLayers[i]);
1661 Rect cursorPos = layer->getPosition(hw);
1662 hwc.setCursorPositionAsync(id, cursorPos);
1663 break;
1664 }
1665 }
1666}
1667
1668void SurfaceFlinger::commitTransaction()
1669{
1670 if (!mLayersPendingRemoval.isEmpty()) {
1671 // Notify removed layers now that they can't be drawn from
1672 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1673 mLayersPendingRemoval[i]->onRemoved();
1674 }
1675 mLayersPendingRemoval.clear();
1676 }
1677
1678 // If this transaction is part of a window animation then the next frame
1679 // we composite should be considered an animation as well.
1680 mAnimCompositionPending = mAnimTransactionPending;
1681
1682 mDrawingState = mCurrentState;
1683 mTransactionPending = false;
1684 mAnimTransactionPending = false;
1685 mTransactionCV.broadcast();
1686}
1687
1688void SurfaceFlinger::computeVisibleRegions(
1689 const LayerVector& currentLayers, uint32_t layerStack,
1690 Region& outDirtyRegion, Region& outOpaqueRegion)
1691{
1692 ATRACE_CALL();
1693
1694 Region aboveOpaqueLayers;
1695 Region aboveCoveredLayers;
1696 Region dirty;
1697
1698 outDirtyRegion.clear();
1699
1700 size_t i = currentLayers.size();
1701 while (i--) {
1702 const sp<Layer>& layer = currentLayers[i];
1703
1704 // start with the whole surface at its current location
1705 const Layer::State& s(layer->getDrawingState());
1706
1707 // only consider the layers on the given layer stack
1708 if (s.layerStack != layerStack)
1709 continue;
1710
1711 /*
1712 * opaqueRegion: area of a surface that is fully opaque.
1713 */
1714 Region opaqueRegion;
1715
1716 /*
1717 * visibleRegion: area of a surface that is visible on screen
1718 * and not fully transparent. This is essentially the layer's
1719 * footprint minus the opaque regions above it.
1720 * Areas covered by a translucent surface are considered visible.
1721 */
1722 Region visibleRegion;
1723
1724 /*
1725 * coveredRegion: area of a surface that is covered by all
1726 * visible regions above it (which includes the translucent areas).
1727 */
1728 Region coveredRegion;
1729
1730 /*
1731 * transparentRegion: area of a surface that is hinted to be completely
1732 * transparent. This is only used to tell when the layer has no visible
1733 * non-transparent regions and can be removed from the layer list. It
1734 * does not affect the visibleRegion of this layer or any layers
1735 * beneath it. The hint may not be correct if apps don't respect the
1736 * SurfaceView restrictions (which, sadly, some don't).
1737 */
1738 Region transparentRegion;
1739
1740
1741 // handle hidden surfaces by setting the visible region to empty
1742 if (CC_LIKELY(layer->isVisible())) {
1743 const bool translucent = !layer->isOpaque(s);
Robert Carr3dcabfa2016-03-01 18:36:58 -08001744 Rect bounds(s.active.transform.transform(layer->computeBounds()));
Dan Stoza9e56aa02015-11-02 13:00:03 -08001745 visibleRegion.set(bounds);
1746 if (!visibleRegion.isEmpty()) {
1747 // Remove the transparent area from the visible region
1748 if (translucent) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001749 const Transform tr(s.active.transform);
Dan Stoza22f7fc42016-05-10 16:19:53 -07001750 if (tr.preserveRects()) {
1751 // transform the transparent region
1752 transparentRegion = tr.transform(s.activeTransparentRegion);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001753 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07001754 // transformation too complex, can't do the
1755 // transparent region optimization.
1756 transparentRegion.clear();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001757 }
1758 }
1759
1760 // compute the opaque region
Robert Carr3dcabfa2016-03-01 18:36:58 -08001761 const int32_t layerOrientation = s.active.transform.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001762 if (s.alpha==255 && !translucent &&
1763 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1764 // the opaque region is the layer's footprint
1765 opaqueRegion = visibleRegion;
1766 }
1767 }
1768 }
1769
1770 // Clip the covered region to the visible region
1771 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1772
1773 // Update aboveCoveredLayers for next (lower) layer
1774 aboveCoveredLayers.orSelf(visibleRegion);
1775
1776 // subtract the opaque region covered by the layers above us
1777 visibleRegion.subtractSelf(aboveOpaqueLayers);
1778
1779 // compute this layer's dirty region
1780 if (layer->contentDirty) {
1781 // we need to invalidate the whole region
1782 dirty = visibleRegion;
1783 // as well, as the old visible region
1784 dirty.orSelf(layer->visibleRegion);
1785 layer->contentDirty = false;
1786 } else {
1787 /* compute the exposed region:
1788 * the exposed region consists of two components:
1789 * 1) what's VISIBLE now and was COVERED before
1790 * 2) what's EXPOSED now less what was EXPOSED before
1791 *
1792 * note that (1) is conservative, we start with the whole
1793 * visible region but only keep what used to be covered by
1794 * something -- which mean it may have been exposed.
1795 *
1796 * (2) handles areas that were not covered by anything but got
1797 * exposed because of a resize.
1798 */
1799 const Region newExposed = visibleRegion - coveredRegion;
1800 const Region oldVisibleRegion = layer->visibleRegion;
1801 const Region oldCoveredRegion = layer->coveredRegion;
1802 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1803 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1804 }
1805 dirty.subtractSelf(aboveOpaqueLayers);
1806
1807 // accumulate to the screen dirty region
1808 outDirtyRegion.orSelf(dirty);
1809
1810 // Update aboveOpaqueLayers for next (lower) layer
1811 aboveOpaqueLayers.orSelf(opaqueRegion);
1812
1813 // Store the visible region in screen space
1814 layer->setVisibleRegion(visibleRegion);
1815 layer->setCoveredRegion(coveredRegion);
1816 layer->setVisibleNonTransparentRegion(
1817 visibleRegion.subtract(transparentRegion));
1818 }
1819
1820 outOpaqueRegion = aboveOpaqueLayers;
1821}
1822
1823void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1824 const Region& dirty) {
1825 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1826 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1827 if (hw->getLayerStack() == layerStack) {
1828 hw->dirtyRegion.orSelf(dirty);
1829 }
1830 }
1831}
1832
1833bool SurfaceFlinger::handlePageFlip()
1834{
1835 Region dirtyRegion;
1836
1837 bool visibleRegions = false;
1838 const LayerVector& layers(mDrawingState.layersSortedByZ);
1839 bool frameQueued = false;
1840
1841 // Store the set of layers that need updates. This set must not change as
1842 // buffers are being latched, as this could result in a deadlock.
1843 // Example: Two producers share the same command stream and:
1844 // 1.) Layer 0 is latched
1845 // 2.) Layer 0 gets a new frame
1846 // 2.) Layer 1 gets a new frame
1847 // 3.) Layer 1 is latched.
1848 // Display is now waiting on Layer 1's frame, which is behind layer 0's
1849 // second frame. But layer 0's second frame could be waiting on display.
1850 Vector<Layer*> layersWithQueuedFrames;
1851 for (size_t i = 0, count = layers.size(); i<count ; i++) {
1852 const sp<Layer>& layer(layers[i]);
1853 if (layer->hasQueuedFrame()) {
1854 frameQueued = true;
1855 if (layer->shouldPresentNow(mPrimaryDispSync)) {
1856 layersWithQueuedFrames.push_back(layer.get());
1857 } else {
1858 layer->useEmptyDamage();
1859 }
1860 } else {
1861 layer->useEmptyDamage();
1862 }
1863 }
1864 for (size_t i = 0, count = layersWithQueuedFrames.size() ; i<count ; i++) {
1865 Layer* layer = layersWithQueuedFrames[i];
1866 const Region dirty(layer->latchBuffer(visibleRegions));
1867 layer->useSurfaceDamage();
1868 const Layer::State& s(layer->getDrawingState());
1869 invalidateLayerStack(s.layerStack, dirty);
1870 }
1871
1872 mVisibleRegionsDirty |= visibleRegions;
1873
1874 // If we will need to wake up at some time in the future to deal with a
1875 // queued frame that shouldn't be displayed during this vsync period, wake
1876 // up during the next vsync period to check again.
1877 if (frameQueued && layersWithQueuedFrames.empty()) {
1878 signalLayerUpdate();
1879 }
1880
1881 // Only continue with the refresh if there is actually new work to do
1882 return !layersWithQueuedFrames.empty();
1883}
1884
1885void SurfaceFlinger::invalidateHwcGeometry()
1886{
1887 mHwWorkListDirty = true;
1888}
1889
1890
1891void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
1892 const Region& inDirtyRegion)
1893{
1894 // We only need to actually compose the display if:
1895 // 1) It is being handled by hardware composer, which may need this to
1896 // keep its virtual display state machine in sync, or
1897 // 2) There is work to be done (the dirty region isn't empty)
1898 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
1899 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
1900 return;
1901 }
1902
1903 Region dirtyRegion(inDirtyRegion);
1904
1905 // compute the invalid region
1906 hw->swapRegion.orSelf(dirtyRegion);
1907
1908 uint32_t flags = hw->getFlags();
1909 if (flags & DisplayDevice::SWAP_RECTANGLE) {
1910 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1911 // takes a rectangle, we must make sure to update that whole
1912 // rectangle in that case
1913 dirtyRegion.set(hw->swapRegion.bounds());
1914 } else {
1915 if (flags & DisplayDevice::PARTIAL_UPDATES) {
1916 // We need to redraw the rectangle that will be updated
1917 // (pushed to the framebuffer).
1918 // This is needed because PARTIAL_UPDATES only takes one
1919 // rectangle instead of a region (see DisplayDevice::flip())
1920 dirtyRegion.set(hw->swapRegion.bounds());
1921 } else {
1922 // we need to redraw everything (the whole screen)
1923 dirtyRegion.set(hw->bounds());
1924 hw->swapRegion = dirtyRegion;
1925 }
1926 }
1927
1928 if (CC_LIKELY(!mDaltonize && !mHasColorMatrix)) {
1929 if (!doComposeSurfaces(hw, dirtyRegion)) return;
1930 } else {
1931 RenderEngine& engine(getRenderEngine());
1932 mat4 colorMatrix = mColorMatrix;
1933 if (mDaltonize) {
1934 colorMatrix = colorMatrix * mDaltonizer();
1935 }
1936 mat4 oldMatrix = engine.setupColorTransform(colorMatrix);
1937 doComposeSurfaces(hw, dirtyRegion);
1938 engine.setupColorTransform(oldMatrix);
1939 }
1940
1941 // update the swap region and clear the dirty region
1942 hw->swapRegion.orSelf(dirtyRegion);
1943
1944 // swap buffers (presentation)
1945 hw->swapBuffers(getHwComposer());
1946}
1947
1948bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
1949{
1950 RenderEngine& engine(getRenderEngine());
1951 const int32_t id = hw->getHwcDisplayId();
1952 HWComposer& hwc(getHwComposer());
1953 HWComposer::LayerListIterator cur = hwc.begin(id);
1954 const HWComposer::LayerListIterator end = hwc.end(id);
1955
1956 bool hasGlesComposition = hwc.hasGlesComposition(id);
1957 if (hasGlesComposition) {
1958 if (!hw->makeCurrent(mEGLDisplay, mEGLContext)) {
1959 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
1960 hw->getDisplayName().string());
1961 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
1962 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
1963 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
1964 }
1965 return false;
1966 }
1967
1968 // Never touch the framebuffer if we don't have any framebuffer layers
1969 const bool hasHwcComposition = hwc.hasHwcComposition(id);
1970 if (hasHwcComposition) {
1971 // when using overlays, we assume a fully transparent framebuffer
1972 // NOTE: we could reduce how much we need to clear, for instance
1973 // remove where there are opaque FB layers. however, on some
1974 // GPUs doing a "clean slate" clear might be more efficient.
1975 // We'll revisit later if needed.
1976 engine.clearWithColor(0, 0, 0, 0);
1977 } else {
1978 // we start with the whole screen area
1979 const Region bounds(hw->getBounds());
1980
1981 // we remove the scissor part
1982 // we're left with the letterbox region
1983 // (common case is that letterbox ends-up being empty)
1984 const Region letterbox(bounds.subtract(hw->getScissor()));
1985
1986 // compute the area to clear
1987 Region region(hw->undefinedRegion.merge(letterbox));
1988
1989 // but limit it to the dirty region
1990 region.andSelf(dirty);
1991
1992 // screen is already cleared here
1993 if (!region.isEmpty()) {
1994 // can happen with SurfaceView
1995 drawWormhole(hw, region);
1996 }
1997 }
1998
1999 if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
2000 // just to be on the safe side, we don't set the
2001 // scissor on the main display. It should never be needed
2002 // anyways (though in theory it could since the API allows it).
2003 const Rect& bounds(hw->getBounds());
2004 const Rect& scissor(hw->getScissor());
2005 if (scissor != bounds) {
2006 // scissor doesn't match the screen's dimensions, so we
2007 // need to clear everything outside of it and enable
2008 // the GL scissor so we don't draw anything where we shouldn't
2009
2010 // enable scissor for this frame
2011 const uint32_t height = hw->getHeight();
2012 engine.setScissor(scissor.left, height - scissor.bottom,
2013 scissor.getWidth(), scissor.getHeight());
2014 }
2015 }
2016 }
2017
2018 /*
2019 * and then, render the layers targeted at the framebuffer
2020 */
2021
2022 const Vector< sp<Layer> >& layers(hw->getVisibleLayersSortedByZ());
2023 const size_t count = layers.size();
2024 const Transform& tr = hw->getTransform();
2025 if (cur != end) {
2026 // we're using h/w composer
2027 for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
2028 const sp<Layer>& layer(layers[i]);
2029 const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
2030 if (!clip.isEmpty()) {
2031 switch (cur->getCompositionType()) {
2032 case HWC_CURSOR_OVERLAY:
2033 case HWC_OVERLAY: {
2034 const Layer::State& state(layer->getDrawingState());
2035 if ((cur->getHints() & HWC_HINT_CLEAR_FB)
2036 && i
2037 && layer->isOpaque(state) && (state.alpha == 0xFF)
2038 && hasGlesComposition) {
2039 // never clear the very first layer since we're
2040 // guaranteed the FB is already cleared
2041 layer->clearWithOpenGL(hw, clip);
2042 }
2043 break;
2044 }
2045 case HWC_FRAMEBUFFER: {
2046 layer->draw(hw, clip);
2047 break;
2048 }
2049 case HWC_FRAMEBUFFER_TARGET: {
2050 // this should not happen as the iterator shouldn't
2051 // let us get there.
2052 ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%zu)", i);
2053 break;
2054 }
2055 }
2056 }
2057 layer->setAcquireFence(hw, *cur);
2058 }
2059 } else {
2060 // we're not using h/w composer
2061 for (size_t i=0 ; i<count ; ++i) {
2062 const sp<Layer>& layer(layers[i]);
2063 const Region clip(dirty.intersect(
2064 tr.transform(layer->visibleRegion)));
2065 if (!clip.isEmpty()) {
2066 layer->draw(hw, clip);
2067 }
2068 }
2069 }
2070
2071 // disable scissor at the end of the frame
2072 engine.disableScissor();
2073 return true;
2074}
2075
2076void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
2077 const int32_t height = hw->getHeight();
2078 RenderEngine& engine(getRenderEngine());
2079 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
2080}
2081
2082status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
2083 const sp<IBinder>& handle,
2084 const sp<IGraphicBufferProducer>& gbc,
2085 const sp<Layer>& lbc)
2086{
2087 // add this layer to the current state list
2088 {
2089 Mutex::Autolock _l(mStateLock);
2090 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2091 return NO_MEMORY;
2092 }
2093 mCurrentState.layersSortedByZ.add(lbc);
2094 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2095 }
2096
2097 // attach this layer to the client
2098 client->attachLayer(handle, lbc);
2099
2100 return NO_ERROR;
2101}
2102
2103status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
2104 Mutex::Autolock _l(mStateLock);
2105 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
2106 if (index >= 0) {
2107 mLayersPendingRemoval.push(layer);
2108 mLayersRemoved = true;
2109 setTransactionFlags(eTransactionNeeded);
2110 return NO_ERROR;
2111 }
2112 return status_t(index);
2113}
2114
2115uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
2116 return android_atomic_release_load(&mTransactionFlags);
2117}
2118
2119uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
2120 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2121}
2122
2123uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
2124 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2125 if ((old & flags)==0) { // wake the server up
2126 signalTransaction();
2127 }
2128 return old;
2129}
2130
2131void SurfaceFlinger::setTransactionState(
2132 const Vector<ComposerState>& state,
2133 const Vector<DisplayState>& displays,
2134 uint32_t flags)
2135{
2136 ATRACE_CALL();
2137 Mutex::Autolock _l(mStateLock);
2138 uint32_t transactionFlags = 0;
2139
2140 if (flags & eAnimation) {
2141 // For window updates that are part of an animation we must wait for
2142 // previous animation "frames" to be handled.
2143 while (mAnimTransactionPending) {
2144 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2145 if (CC_UNLIKELY(err != NO_ERROR)) {
2146 // just in case something goes wrong in SF, return to the
2147 // caller after a few seconds.
2148 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2149 "waiting for previous animation frame");
2150 mAnimTransactionPending = false;
2151 break;
2152 }
2153 }
2154 }
2155
2156 size_t count = displays.size();
2157 for (size_t i=0 ; i<count ; i++) {
2158 const DisplayState& s(displays[i]);
2159 transactionFlags |= setDisplayStateLocked(s);
2160 }
2161
2162 count = state.size();
2163 for (size_t i=0 ; i<count ; i++) {
2164 const ComposerState& s(state[i]);
2165 // Here we need to check that the interface we're given is indeed
2166 // one of our own. A malicious client could give us a NULL
2167 // IInterface, or one of its own or even one of our own but a
2168 // different type. All these situations would cause us to crash.
2169 //
2170 // NOTE: it would be better to use RTTI as we could directly check
2171 // that we have a Client*. however, RTTI is disabled in Android.
2172 if (s.client != NULL) {
2173 sp<IBinder> binder = IInterface::asBinder(s.client);
2174 if (binder != NULL) {
2175 String16 desc(binder->getInterfaceDescriptor());
2176 if (desc == ISurfaceComposerClient::descriptor) {
2177 sp<Client> client( static_cast<Client *>(s.client.get()) );
2178 transactionFlags |= setClientStateLocked(client, s.state);
2179 }
2180 }
2181 }
2182 }
2183
2184 if (transactionFlags) {
2185 // this triggers the transaction
2186 setTransactionFlags(transactionFlags);
2187
2188 // if this is a synchronous transaction, wait for it to take effect
2189 // before returning.
2190 if (flags & eSynchronous) {
2191 mTransactionPending = true;
2192 }
2193 if (flags & eAnimation) {
2194 mAnimTransactionPending = true;
2195 }
2196 while (mTransactionPending) {
2197 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2198 if (CC_UNLIKELY(err != NO_ERROR)) {
2199 // just in case something goes wrong in SF, return to the
2200 // called after a few seconds.
2201 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2202 mTransactionPending = false;
2203 break;
2204 }
2205 }
2206 }
2207}
2208
2209uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2210{
2211 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2212 if (dpyIdx < 0)
2213 return 0;
2214
2215 uint32_t flags = 0;
2216 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
2217 if (disp.isValid()) {
2218 const uint32_t what = s.what;
2219 if (what & DisplayState::eSurfaceChanged) {
2220 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
2221 disp.surface = s.surface;
2222 flags |= eDisplayTransactionNeeded;
2223 }
2224 }
2225 if (what & DisplayState::eLayerStackChanged) {
2226 if (disp.layerStack != s.layerStack) {
2227 disp.layerStack = s.layerStack;
2228 flags |= eDisplayTransactionNeeded;
2229 }
2230 }
2231 if (what & DisplayState::eDisplayProjectionChanged) {
2232 if (disp.orientation != s.orientation) {
2233 disp.orientation = s.orientation;
2234 flags |= eDisplayTransactionNeeded;
2235 }
2236 if (disp.frame != s.frame) {
2237 disp.frame = s.frame;
2238 flags |= eDisplayTransactionNeeded;
2239 }
2240 if (disp.viewport != s.viewport) {
2241 disp.viewport = s.viewport;
2242 flags |= eDisplayTransactionNeeded;
2243 }
2244 }
2245 if (what & DisplayState::eDisplaySizeChanged) {
2246 if (disp.width != s.width) {
2247 disp.width = s.width;
2248 flags |= eDisplayTransactionNeeded;
2249 }
2250 if (disp.height != s.height) {
2251 disp.height = s.height;
2252 flags |= eDisplayTransactionNeeded;
2253 }
2254 }
2255 }
2256 return flags;
2257}
2258
2259uint32_t SurfaceFlinger::setClientStateLocked(
2260 const sp<Client>& client,
2261 const layer_state_t& s)
2262{
2263 uint32_t flags = 0;
2264 sp<Layer> layer(client->getLayerUser(s.surface));
2265 if (layer != 0) {
2266 const uint32_t what = s.what;
2267 if (what & layer_state_t::ePositionChanged) {
2268 if (layer->setPosition(s.x, s.y))
2269 flags |= eTraversalNeeded;
2270 }
2271 if (what & layer_state_t::eLayerChanged) {
2272 // NOTE: index needs to be calculated before we update the state
2273 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2274 if (layer->setLayer(s.z) && idx >= 0) {
2275 mCurrentState.layersSortedByZ.removeAt(idx);
2276 mCurrentState.layersSortedByZ.add(layer);
2277 // we need traversal (state changed)
2278 // AND transaction (list changed)
2279 flags |= eTransactionNeeded|eTraversalNeeded;
2280 }
2281 }
2282 if (what & layer_state_t::eSizeChanged) {
2283 if (layer->setSize(s.w, s.h)) {
2284 flags |= eTraversalNeeded;
2285 }
2286 }
2287 if (what & layer_state_t::eAlphaChanged) {
2288 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
2289 flags |= eTraversalNeeded;
2290 }
2291 if (what & layer_state_t::eMatrixChanged) {
2292 if (layer->setMatrix(s.matrix))
2293 flags |= eTraversalNeeded;
2294 }
2295 if (what & layer_state_t::eTransparentRegionChanged) {
2296 if (layer->setTransparentRegionHint(s.transparentRegion))
2297 flags |= eTraversalNeeded;
2298 }
2299 if (what & layer_state_t::eFlagsChanged) {
2300 if (layer->setFlags(s.flags, s.mask))
2301 flags |= eTraversalNeeded;
2302 }
2303 if (what & layer_state_t::eCropChanged) {
2304 if (layer->setCrop(s.crop))
2305 flags |= eTraversalNeeded;
2306 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002307 if (what & layer_state_t::eFinalCropChanged) {
2308 if (layer->setFinalCrop(s.finalCrop))
2309 flags |= eTraversalNeeded;
2310 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002311 if (what & layer_state_t::eLayerStackChanged) {
2312 // NOTE: index needs to be calculated before we update the state
2313 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2314 if (layer->setLayerStack(s.layerStack) && idx >= 0) {
2315 mCurrentState.layersSortedByZ.removeAt(idx);
2316 mCurrentState.layersSortedByZ.add(layer);
2317 // we need traversal (state changed)
2318 // AND transaction (list changed)
2319 flags |= eTransactionNeeded|eTraversalNeeded;
2320 }
2321 }
2322 if (what & layer_state_t::eDeferTransaction) {
2323 layer->deferTransactionUntil(s.handle, s.frameNumber);
2324 // We don't trigger a traversal here because if no other state is
2325 // changed, we don't want this to cause any more work
2326 }
Robert Carrc3574f72016-03-24 12:19:32 -07002327 if (what & layer_state_t::eOverrideScalingModeChanged) {
2328 layer->setOverrideScalingMode(s.overrideScalingMode);
2329 // We don't trigger a traversal here because if no other state is
2330 // changed, we don't want this to cause any more work
2331 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002332 }
2333 return flags;
2334}
2335
2336status_t SurfaceFlinger::createLayer(
2337 const String8& name,
2338 const sp<Client>& client,
2339 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2340 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
2341{
2342 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
2343 if (int32_t(w|h) < 0) {
2344 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
2345 int(w), int(h));
2346 return BAD_VALUE;
2347 }
2348
2349 status_t result = NO_ERROR;
2350
2351 sp<Layer> layer;
2352
2353 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2354 case ISurfaceComposerClient::eFXSurfaceNormal:
2355 result = createNormalLayer(client,
2356 name, w, h, flags, format,
2357 handle, gbp, &layer);
2358 break;
2359 case ISurfaceComposerClient::eFXSurfaceDim:
2360 result = createDimLayer(client,
2361 name, w, h, flags,
2362 handle, gbp, &layer);
2363 break;
2364 default:
2365 result = BAD_VALUE;
2366 break;
2367 }
2368
2369 if (result != NO_ERROR) {
2370 return result;
2371 }
2372
2373 result = addClientLayer(client, *handle, *gbp, layer);
2374 if (result != NO_ERROR) {
2375 return result;
2376 }
2377
2378 setTransactionFlags(eTransactionNeeded);
2379 return result;
2380}
2381
2382status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2383 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2384 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2385{
2386 // initialize the surfaces
2387 switch (format) {
2388 case PIXEL_FORMAT_TRANSPARENT:
2389 case PIXEL_FORMAT_TRANSLUCENT:
2390 format = PIXEL_FORMAT_RGBA_8888;
2391 break;
2392 case PIXEL_FORMAT_OPAQUE:
2393 format = PIXEL_FORMAT_RGBX_8888;
2394 break;
2395 }
2396
2397 *outLayer = new Layer(this, client, name, w, h, flags);
2398 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2399 if (err == NO_ERROR) {
2400 *handle = (*outLayer)->getHandle();
2401 *gbp = (*outLayer)->getProducer();
2402 }
2403
2404 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2405 return err;
2406}
2407
2408status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2409 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2410 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2411{
2412 *outLayer = new LayerDim(this, client, name, w, h, flags);
2413 *handle = (*outLayer)->getHandle();
2414 *gbp = (*outLayer)->getProducer();
2415 return NO_ERROR;
2416}
2417
2418status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
2419{
2420 // called by the window manager when it wants to remove a Layer
2421 status_t err = NO_ERROR;
2422 sp<Layer> l(client->getLayerUser(handle));
2423 if (l != NULL) {
2424 err = removeLayer(l);
2425 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2426 "error removing layer=%p (%s)", l.get(), strerror(-err));
2427 }
2428 return err;
2429}
2430
2431status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
2432{
2433 // called by ~LayerCleaner() when all references to the IBinder (handle)
2434 // are gone
2435 status_t err = NO_ERROR;
2436 sp<Layer> l(layer.promote());
2437 if (l != NULL) {
2438 err = removeLayer(l);
2439 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2440 "error removing layer=%p (%s)", l.get(), strerror(-err));
2441 }
2442 return err;
2443}
2444
2445// ---------------------------------------------------------------------------
2446
2447void SurfaceFlinger::onInitializeDisplays() {
2448 // reset screen orientation and use primary layer stack
2449 Vector<ComposerState> state;
2450 Vector<DisplayState> displays;
2451 DisplayState d;
2452 d.what = DisplayState::eDisplayProjectionChanged |
2453 DisplayState::eLayerStackChanged;
2454 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
2455 d.layerStack = 0;
2456 d.orientation = DisplayState::eOrientationDefault;
2457 d.frame.makeInvalid();
2458 d.viewport.makeInvalid();
2459 d.width = 0;
2460 d.height = 0;
2461 displays.add(d);
2462 setTransactionState(state, displays, 0);
2463 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
2464
2465 const nsecs_t period =
2466 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2467 mAnimFrameTracker.setDisplayRefreshPeriod(period);
2468}
2469
2470void SurfaceFlinger::initializeDisplays() {
2471 class MessageScreenInitialized : public MessageBase {
2472 SurfaceFlinger* flinger;
2473 public:
2474 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2475 virtual bool handler() {
2476 flinger->onInitializeDisplays();
2477 return true;
2478 }
2479 };
2480 sp<MessageBase> msg = new MessageScreenInitialized(this);
2481 postMessageAsync(msg); // we may be called from main thread, use async message
2482}
2483
2484void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2485 int mode) {
2486 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2487 this);
2488 int32_t type = hw->getDisplayType();
2489 int currentMode = hw->getPowerMode();
2490
2491 if (mode == currentMode) {
2492 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
2493 return;
2494 }
2495
2496 hw->setPowerMode(mode);
2497 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2498 ALOGW("Trying to set power mode for virtual display");
2499 return;
2500 }
2501
2502 if (currentMode == HWC_POWER_MODE_OFF) {
2503 getHwComposer().setPowerMode(type, mode);
2504 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2505 // FIXME: eventthread only knows about the main display right now
2506 mEventThread->onScreenAcquired();
2507 resyncToHardwareVsync(true);
2508 }
2509
2510 mVisibleRegionsDirty = true;
2511 mHasPoweredOff = true;
2512 repaintEverything();
2513 } else if (mode == HWC_POWER_MODE_OFF) {
2514 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2515 disableHardwareVsync(true); // also cancels any in-progress resync
2516
2517 // FIXME: eventthread only knows about the main display right now
2518 mEventThread->onScreenReleased();
2519 }
2520
2521 getHwComposer().setPowerMode(type, mode);
2522 mVisibleRegionsDirty = true;
2523 // from this point on, SF will stop drawing on this display
2524 } else {
2525 getHwComposer().setPowerMode(type, mode);
2526 }
2527}
2528
2529void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2530 class MessageSetPowerMode: public MessageBase {
2531 SurfaceFlinger& mFlinger;
2532 sp<IBinder> mDisplay;
2533 int mMode;
2534 public:
2535 MessageSetPowerMode(SurfaceFlinger& flinger,
2536 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2537 mDisplay(disp) { mMode = mode; }
2538 virtual bool handler() {
2539 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2540 if (hw == NULL) {
2541 ALOGE("Attempt to set power mode = %d for null display %p",
2542 mMode, mDisplay.get());
2543 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2544 ALOGW("Attempt to set power mode = %d for virtual display",
2545 mMode);
2546 } else {
2547 mFlinger.setPowerModeInternal(hw, mMode);
2548 }
2549 return true;
2550 }
2551 };
2552 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
2553 postMessageSync(msg);
2554}
2555
2556// ---------------------------------------------------------------------------
2557
2558status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2559{
2560 String8 result;
2561
2562 IPCThreadState* ipc = IPCThreadState::self();
2563 const int pid = ipc->getCallingPid();
2564 const int uid = ipc->getCallingUid();
2565 if ((uid != AID_SHELL) &&
2566 !PermissionCache::checkPermission(sDump, pid, uid)) {
2567 result.appendFormat("Permission Denial: "
2568 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
2569 } else {
2570 // Try to get the main lock, but give up after one second
2571 // (this would indicate SF is stuck, but we want to be able to
2572 // print something in dumpsys).
2573 status_t err = mStateLock.timedLock(s2ns(1));
2574 bool locked = (err == NO_ERROR);
2575 if (!locked) {
2576 result.appendFormat(
2577 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2578 "dumping anyways (no locks held)\n", strerror(-err), err);
2579 }
2580
2581 bool dumpAll = true;
2582 size_t index = 0;
2583 size_t numArgs = args.size();
2584 if (numArgs) {
2585 if ((index < numArgs) &&
2586 (args[index] == String16("--list"))) {
2587 index++;
2588 listLayersLocked(args, index, result);
2589 dumpAll = false;
2590 }
2591
2592 if ((index < numArgs) &&
2593 (args[index] == String16("--latency"))) {
2594 index++;
2595 dumpStatsLocked(args, index, result);
2596 dumpAll = false;
2597 }
2598
2599 if ((index < numArgs) &&
2600 (args[index] == String16("--latency-clear"))) {
2601 index++;
2602 clearStatsLocked(args, index, result);
2603 dumpAll = false;
2604 }
2605
2606 if ((index < numArgs) &&
2607 (args[index] == String16("--dispsync"))) {
2608 index++;
2609 mPrimaryDispSync.dump(result);
2610 dumpAll = false;
2611 }
2612
2613 if ((index < numArgs) &&
2614 (args[index] == String16("--static-screen"))) {
2615 index++;
2616 dumpStaticScreenStats(result);
2617 dumpAll = false;
2618 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002619
Pablo Ceballos69a1a382016-03-30 15:28:05 -07002620#ifdef ENABLE_FENCE_TRACKING
Pablo Ceballos40845df2016-01-25 17:41:15 -08002621 if ((index < numArgs) &&
2622 (args[index] == String16("--fences"))) {
2623 index++;
2624 mFenceTracker.dump(&result);
2625 dumpAll = false;
2626 }
Pablo Ceballos69a1a382016-03-30 15:28:05 -07002627#endif
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
2748void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2749 String8& result) const
2750{
2751 bool colorize = false;
2752 if (index < args.size()
2753 && (args[index] == String16("--color"))) {
2754 colorize = true;
2755 index++;
2756 }
2757
2758 Colorizer colorizer(colorize);
2759
2760 // figure out if we're stuck somewhere
2761 const nsecs_t now = systemTime();
2762 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2763 const nsecs_t inTransaction(mDebugInTransaction);
2764 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2765 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2766
2767 /*
2768 * Dump library configuration.
2769 */
2770
2771 colorizer.bold(result);
2772 result.append("Build configuration:");
2773 colorizer.reset(result);
2774 appendSfConfigString(result);
2775 appendUiConfigString(result);
2776 appendGuiConfigString(result);
2777 result.append("\n");
2778
2779 colorizer.bold(result);
2780 result.append("Sync configuration: ");
2781 colorizer.reset(result);
2782 result.append(SyncFeatures::getInstance().toString());
2783 result.append("\n");
2784
2785 colorizer.bold(result);
2786 result.append("DispSync configuration: ");
2787 colorizer.reset(result);
2788 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
2789 "present offset %d ns (refresh %" PRId64 " ns)",
2790 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, PRESENT_TIME_OFFSET_FROM_VSYNC_NS,
2791 mHwc->getRefreshPeriod(HWC_DISPLAY_PRIMARY));
2792 result.append("\n");
2793
2794 // Dump static screen stats
2795 result.append("\n");
2796 dumpStaticScreenStats(result);
2797 result.append("\n");
2798
2799 /*
2800 * Dump the visible layer list
2801 */
2802 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2803 const size_t count = currentLayers.size();
2804 colorizer.bold(result);
2805 result.appendFormat("Visible layers (count = %zu)\n", count);
2806 colorizer.reset(result);
2807 for (size_t i=0 ; i<count ; i++) {
2808 const sp<Layer>& layer(currentLayers[i]);
2809 layer->dump(result, colorizer);
2810 }
2811
2812 /*
2813 * Dump Display state
2814 */
2815
2816 colorizer.bold(result);
2817 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
2818 colorizer.reset(result);
2819 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2820 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
2821 hw->dump(result);
2822 }
2823
2824 /*
2825 * Dump SurfaceFlinger global state
2826 */
2827
2828 colorizer.bold(result);
2829 result.append("SurfaceFlinger global state:\n");
2830 colorizer.reset(result);
2831
2832 HWComposer& hwc(getHwComposer());
2833 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2834
2835 colorizer.bold(result);
2836 result.appendFormat("EGL implementation : %s\n",
2837 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2838 colorizer.reset(result);
2839 result.appendFormat("%s\n",
2840 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
2841
2842 mRenderEngine->dump(result);
2843
2844 hw->undefinedRegion.dump(result, "undefinedRegion");
2845 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
2846 hw->getOrientation(), hw->isDisplayOn());
2847 result.appendFormat(
2848 " last eglSwapBuffers() time: %f us\n"
2849 " last transaction time : %f us\n"
2850 " transaction-flags : %08x\n"
2851 " refresh-rate : %f fps\n"
2852 " x-dpi : %f\n"
2853 " y-dpi : %f\n"
2854 " gpu_to_cpu_unsupported : %d\n"
2855 ,
2856 mLastSwapBufferTime/1000.0,
2857 mLastTransactionTime/1000.0,
2858 mTransactionFlags,
2859 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
2860 hwc.getDpiX(HWC_DISPLAY_PRIMARY),
2861 hwc.getDpiY(HWC_DISPLAY_PRIMARY),
2862 !mGpuToCpuSupported);
2863
2864 result.appendFormat(" eglSwapBuffers time: %f us\n",
2865 inSwapBuffersDuration/1000.0);
2866
2867 result.appendFormat(" transaction time: %f us\n",
2868 inTransactionDuration/1000.0);
2869
2870 /*
2871 * VSYNC state
2872 */
2873 mEventThread->dump(result);
2874
2875 /*
2876 * Dump HWComposer state
2877 */
2878 colorizer.bold(result);
2879 result.append("h/w composer state:\n");
2880 colorizer.reset(result);
2881 result.appendFormat(" h/w composer %s and %s\n",
2882 hwc.initCheck()==NO_ERROR ? "present" : "not present",
2883 (mDebugDisableHWC || mDebugRegion || mDaltonize
2884 || mHasColorMatrix) ? "disabled" : "enabled");
2885 hwc.dump(result);
2886
2887 /*
2888 * Dump gralloc state
2889 */
2890 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2891 alloc.dump(result);
2892}
2893
2894const Vector< sp<Layer> >&
2895SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
2896 // Note: mStateLock is held here
2897 wp<IBinder> dpy;
2898 for (size_t i=0 ; i<mDisplays.size() ; i++) {
2899 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2900 dpy = mDisplays.keyAt(i);
2901 break;
2902 }
2903 }
2904 if (dpy == NULL) {
2905 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
2906 // Just use the primary display so we have something to return
2907 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
2908 }
2909 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
2910}
2911
2912bool SurfaceFlinger::startDdmConnection()
2913{
2914 void* libddmconnection_dso =
2915 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2916 if (!libddmconnection_dso) {
2917 return false;
2918 }
2919 void (*DdmConnection_start)(const char* name);
2920 DdmConnection_start =
2921 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
2922 if (!DdmConnection_start) {
2923 dlclose(libddmconnection_dso);
2924 return false;
2925 }
2926 (*DdmConnection_start)(getServiceName());
2927 return true;
2928}
2929
2930status_t SurfaceFlinger::onTransact(
2931 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2932{
2933 switch (code) {
2934 case CREATE_CONNECTION:
2935 case CREATE_DISPLAY:
2936 case SET_TRANSACTION_STATE:
2937 case BOOT_FINISHED:
2938 case CLEAR_ANIMATION_FRAME_STATS:
2939 case GET_ANIMATION_FRAME_STATS:
2940 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07002941 case GET_HDR_CAPABILITIES:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002942 {
2943 // codes that require permission check
2944 IPCThreadState* ipc = IPCThreadState::self();
2945 const int pid = ipc->getCallingPid();
2946 const int uid = ipc->getCallingUid();
2947 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
2948 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
2949 ALOGE("Permission Denial: "
2950 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2951 return PERMISSION_DENIED;
2952 }
2953 break;
2954 }
2955 case CAPTURE_SCREEN:
2956 {
2957 // codes that require permission check
2958 IPCThreadState* ipc = IPCThreadState::self();
2959 const int pid = ipc->getCallingPid();
2960 const int uid = ipc->getCallingUid();
2961 if ((uid != AID_GRAPHICS) &&
2962 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
2963 ALOGE("Permission Denial: "
2964 "can't read framebuffer pid=%d, uid=%d", pid, uid);
2965 return PERMISSION_DENIED;
2966 }
2967 break;
2968 }
2969 }
2970
2971 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2972 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
2973 CHECK_INTERFACE(ISurfaceComposer, data, reply);
2974 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
2975 IPCThreadState* ipc = IPCThreadState::self();
2976 const int pid = ipc->getCallingPid();
2977 const int uid = ipc->getCallingUid();
2978 ALOGE("Permission Denial: "
2979 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2980 return PERMISSION_DENIED;
2981 }
2982 int n;
2983 switch (code) {
2984 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
2985 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
2986 return NO_ERROR;
2987 case 1002: // SHOW_UPDATES
2988 n = data.readInt32();
2989 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
2990 invalidateHwcGeometry();
2991 repaintEverything();
2992 return NO_ERROR;
2993 case 1004:{ // repaint everything
2994 repaintEverything();
2995 return NO_ERROR;
2996 }
2997 case 1005:{ // force transaction
2998 setTransactionFlags(
2999 eTransactionNeeded|
3000 eDisplayTransactionNeeded|
3001 eTraversalNeeded);
3002 return NO_ERROR;
3003 }
3004 case 1006:{ // send empty update
3005 signalRefresh();
3006 return NO_ERROR;
3007 }
3008 case 1008: // toggle use of hw composer
3009 n = data.readInt32();
3010 mDebugDisableHWC = n ? 1 : 0;
3011 invalidateHwcGeometry();
3012 repaintEverything();
3013 return NO_ERROR;
3014 case 1009: // toggle use of transform hint
3015 n = data.readInt32();
3016 mDebugDisableTransformHint = n ? 1 : 0;
3017 invalidateHwcGeometry();
3018 repaintEverything();
3019 return NO_ERROR;
3020 case 1010: // interrogate.
3021 reply->writeInt32(0);
3022 reply->writeInt32(0);
3023 reply->writeInt32(mDebugRegion);
3024 reply->writeInt32(0);
3025 reply->writeInt32(mDebugDisableHWC);
3026 return NO_ERROR;
3027 case 1013: {
3028 Mutex::Autolock _l(mStateLock);
3029 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3030 reply->writeInt32(hw->getPageFlipCount());
3031 return NO_ERROR;
3032 }
3033 case 1014: {
3034 // daltonize
3035 n = data.readInt32();
3036 switch (n % 10) {
3037 case 1: mDaltonizer.setType(Daltonizer::protanomaly); break;
3038 case 2: mDaltonizer.setType(Daltonizer::deuteranomaly); break;
3039 case 3: mDaltonizer.setType(Daltonizer::tritanomaly); break;
3040 }
3041 if (n >= 10) {
3042 mDaltonizer.setMode(Daltonizer::correction);
3043 } else {
3044 mDaltonizer.setMode(Daltonizer::simulation);
3045 }
3046 mDaltonize = n > 0;
3047 invalidateHwcGeometry();
3048 repaintEverything();
3049 return NO_ERROR;
3050 }
3051 case 1015: {
3052 // apply a color matrix
3053 n = data.readInt32();
3054 mHasColorMatrix = n ? 1 : 0;
3055 if (n) {
3056 // color matrix is sent as mat3 matrix followed by vec3
3057 // offset, then packed into a mat4 where the last row is
3058 // the offset and extra values are 0
3059 for (size_t i = 0 ; i < 4; i++) {
3060 for (size_t j = 0; j < 4; j++) {
3061 mColorMatrix[i][j] = data.readFloat();
3062 }
3063 }
3064 } else {
3065 mColorMatrix = mat4();
3066 }
3067 invalidateHwcGeometry();
3068 repaintEverything();
3069 return NO_ERROR;
3070 }
3071 // This is an experimental interface
3072 // Needs to be shifted to proper binder interface when we productize
3073 case 1016: {
3074 n = data.readInt32();
3075 mPrimaryDispSync.setRefreshSkipCount(n);
3076 return NO_ERROR;
3077 }
3078 case 1017: {
3079 n = data.readInt32();
3080 mForceFullDamage = static_cast<bool>(n);
3081 return NO_ERROR;
3082 }
3083 case 1018: { // Modify Choreographer's phase offset
3084 n = data.readInt32();
3085 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3086 return NO_ERROR;
3087 }
3088 case 1019: { // Modify SurfaceFlinger's phase offset
3089 n = data.readInt32();
3090 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3091 return NO_ERROR;
3092 }
3093 }
3094 }
3095 return err;
3096}
3097
3098void SurfaceFlinger::repaintEverything() {
3099 android_atomic_or(1, &mRepaintEverything);
3100 signalTransaction();
3101}
3102
3103// ---------------------------------------------------------------------------
3104// Capture screen into an IGraphiBufferProducer
3105// ---------------------------------------------------------------------------
3106
3107/* The code below is here to handle b/8734824
3108 *
3109 * We create a IGraphicBufferProducer wrapper that forwards all calls
3110 * from the surfaceflinger thread to the calling binder thread, where they
3111 * are executed. This allows the calling thread in the calling process to be
3112 * reused and not depend on having "enough" binder threads to handle the
3113 * requests.
3114 */
3115class GraphicProducerWrapper : public BBinder, public MessageHandler {
3116 /* Parts of GraphicProducerWrapper are run on two different threads,
3117 * communicating by sending messages via Looper but also by shared member
3118 * data. Coherence maintenance is subtle and in places implicit (ugh).
3119 *
3120 * Don't rely on Looper's sendMessage/handleMessage providing
3121 * release/acquire semantics for any data not actually in the Message.
3122 * Data going from surfaceflinger to binder threads needs to be
3123 * synchronized explicitly.
3124 *
3125 * Barrier open/wait do provide release/acquire semantics. This provides
3126 * implicit synchronization for data coming back from binder to
3127 * surfaceflinger threads.
3128 */
3129
3130 sp<IGraphicBufferProducer> impl;
3131 sp<Looper> looper;
3132 status_t result;
3133 bool exitPending;
3134 bool exitRequested;
3135 Barrier barrier;
3136 uint32_t code;
3137 Parcel const* data;
3138 Parcel* reply;
3139
3140 enum {
3141 MSG_API_CALL,
3142 MSG_EXIT
3143 };
3144
3145 /*
3146 * Called on surfaceflinger thread. This is called by our "fake"
3147 * BpGraphicBufferProducer. We package the data and reply Parcel and
3148 * forward them to the binder thread.
3149 */
3150 virtual status_t transact(uint32_t code,
3151 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
3152 this->code = code;
3153 this->data = &data;
3154 this->reply = reply;
3155 if (exitPending) {
3156 // if we've exited, we run the message synchronously right here.
3157 // note (JH): as far as I can tell from looking at the code, this
3158 // never actually happens. if it does, i'm not sure if it happens
3159 // on the surfaceflinger or binder thread.
3160 handleMessage(Message(MSG_API_CALL));
3161 } else {
3162 barrier.close();
3163 // Prevent stores to this->{code, data, reply} from being
3164 // reordered later than the construction of Message.
3165 atomic_thread_fence(memory_order_release);
3166 looper->sendMessage(this, Message(MSG_API_CALL));
3167 barrier.wait();
3168 }
3169 return result;
3170 }
3171
3172 /*
3173 * here we run on the binder thread. All we've got to do is
3174 * call the real BpGraphicBufferProducer.
3175 */
3176 virtual void handleMessage(const Message& message) {
3177 int what = message.what;
3178 // Prevent reads below from happening before the read from Message
3179 atomic_thread_fence(memory_order_acquire);
3180 if (what == MSG_API_CALL) {
3181 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
3182 barrier.open();
3183 } else if (what == MSG_EXIT) {
3184 exitRequested = true;
3185 }
3186 }
3187
3188public:
3189 GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3190 : impl(impl),
3191 looper(new Looper(true)),
3192 result(NO_ERROR),
3193 exitPending(false),
3194 exitRequested(false),
3195 code(0),
3196 data(NULL),
3197 reply(NULL)
3198 {}
3199
3200 // Binder thread
3201 status_t waitForResponse() {
3202 do {
3203 looper->pollOnce(-1);
3204 } while (!exitRequested);
3205 return result;
3206 }
3207
3208 // Client thread
3209 void exit(status_t result) {
3210 this->result = result;
3211 exitPending = true;
3212 // Ensure this->result is visible to the binder thread before it
3213 // handles the message.
3214 atomic_thread_fence(memory_order_release);
3215 looper->sendMessage(this, Message(MSG_EXIT));
3216 }
3217};
3218
3219
3220status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3221 const sp<IGraphicBufferProducer>& producer,
3222 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3223 uint32_t minLayerZ, uint32_t maxLayerZ,
3224 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
3225
3226 if (CC_UNLIKELY(display == 0))
3227 return BAD_VALUE;
3228
3229 if (CC_UNLIKELY(producer == 0))
3230 return BAD_VALUE;
3231
3232 // if we have secure windows on this display, never allow the screen capture
3233 // unless the producer interface is local (i.e.: we can take a screenshot for
3234 // ourselves).
3235 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
3236
3237 // Convert to surfaceflinger's internal rotation type.
3238 Transform::orientation_flags rotationFlags;
3239 switch (rotation) {
3240 case ISurfaceComposer::eRotateNone:
3241 rotationFlags = Transform::ROT_0;
3242 break;
3243 case ISurfaceComposer::eRotate90:
3244 rotationFlags = Transform::ROT_90;
3245 break;
3246 case ISurfaceComposer::eRotate180:
3247 rotationFlags = Transform::ROT_180;
3248 break;
3249 case ISurfaceComposer::eRotate270:
3250 rotationFlags = Transform::ROT_270;
3251 break;
3252 default:
3253 rotationFlags = Transform::ROT_0;
3254 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3255 break;
3256 }
3257
3258 class MessageCaptureScreen : public MessageBase {
3259 SurfaceFlinger* flinger;
3260 sp<IBinder> display;
3261 sp<IGraphicBufferProducer> producer;
3262 Rect sourceCrop;
3263 uint32_t reqWidth, reqHeight;
3264 uint32_t minLayerZ,maxLayerZ;
3265 bool useIdentityTransform;
3266 Transform::orientation_flags rotation;
3267 status_t result;
3268 bool isLocalScreenshot;
3269 public:
3270 MessageCaptureScreen(SurfaceFlinger* flinger,
3271 const sp<IBinder>& display,
3272 const sp<IGraphicBufferProducer>& producer,
3273 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3274 uint32_t minLayerZ, uint32_t maxLayerZ,
3275 bool useIdentityTransform,
3276 Transform::orientation_flags rotation,
3277 bool isLocalScreenshot)
3278 : flinger(flinger), display(display), producer(producer),
3279 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
3280 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
3281 useIdentityTransform(useIdentityTransform),
3282 rotation(rotation), result(PERMISSION_DENIED),
3283 isLocalScreenshot(isLocalScreenshot)
3284 {
3285 }
3286 status_t getResult() const {
3287 return result;
3288 }
3289 virtual bool handler() {
3290 Mutex::Autolock _l(flinger->mStateLock);
3291 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
3292 result = flinger->captureScreenImplLocked(hw, producer,
3293 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3294 useIdentityTransform, rotation, isLocalScreenshot);
3295 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
3296 return true;
3297 }
3298 };
3299
3300 // make sure to process transactions before screenshots -- a transaction
3301 // might already be pending but scheduled for VSYNC; this guarantees we
3302 // will handle it before the screenshot. When VSYNC finally arrives
3303 // the scheduled transaction will be a no-op. If no transactions are
3304 // scheduled at this time, this will end-up being a no-op as well.
3305 mEventQueue.invalidateTransactionNow();
3306
3307 // this creates a "fake" BBinder which will serve as a "fake" remote
3308 // binder to receive the marshaled calls and forward them to the
3309 // real remote (a BpGraphicBufferProducer)
3310 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3311
3312 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3313 // which does the marshaling work forwards to our "fake remote" above.
3314 sp<MessageBase> msg = new MessageCaptureScreen(this,
3315 display, IGraphicBufferProducer::asInterface( wrapper ),
3316 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3317 useIdentityTransform, rotationFlags, isLocalScreenshot);
3318
3319 status_t res = postMessageAsync(msg);
3320 if (res == NO_ERROR) {
3321 res = wrapper->waitForResponse();
3322 }
3323 return res;
3324}
3325
3326
3327void SurfaceFlinger::renderScreenImplLocked(
3328 const sp<const DisplayDevice>& hw,
3329 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3330 uint32_t minLayerZ, uint32_t maxLayerZ,
3331 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
3332{
3333 ATRACE_CALL();
3334 RenderEngine& engine(getRenderEngine());
3335
3336 // get screen geometry
3337 const int32_t hw_w = hw->getWidth();
3338 const int32_t hw_h = hw->getHeight();
3339 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
3340 static_cast<int32_t>(reqHeight) != hw_h;
3341
3342 // if a default or invalid sourceCrop is passed in, set reasonable values
3343 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3344 !sourceCrop.isValid()) {
3345 sourceCrop.setLeftTop(Point(0, 0));
3346 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3347 }
3348
3349 // ensure that sourceCrop is inside screen
3350 if (sourceCrop.left < 0) {
3351 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3352 }
3353 if (sourceCrop.right > hw_w) {
3354 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
3355 }
3356 if (sourceCrop.top < 0) {
3357 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3358 }
3359 if (sourceCrop.bottom > hw_h) {
3360 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
3361 }
3362
3363 // make sure to clear all GL error flags
3364 engine.checkErrors();
3365
3366 // set-up our viewport
3367 engine.setViewportAndProjection(
3368 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
3369 engine.disableTexturing();
3370
3371 // redraw the screen entirely...
3372 engine.clearWithColor(0, 0, 0, 1);
3373
3374 const LayerVector& layers( mDrawingState.layersSortedByZ );
3375 const size_t count = layers.size();
3376 for (size_t i=0 ; i<count ; ++i) {
3377 const sp<Layer>& layer(layers[i]);
3378 const Layer::State& state(layer->getDrawingState());
3379 if (state.layerStack == hw->getLayerStack()) {
3380 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3381 if (layer->isVisible()) {
3382 if (filtering) layer->setFiltering(true);
3383 layer->draw(hw, useIdentityTransform);
3384 if (filtering) layer->setFiltering(false);
3385 }
3386 }
3387 }
3388 }
3389
3390 // compositionComplete is needed for older driver
3391 hw->compositionComplete();
3392 hw->setViewportAndProjection();
3393}
3394
3395
3396status_t SurfaceFlinger::captureScreenImplLocked(
3397 const sp<const DisplayDevice>& hw,
3398 const sp<IGraphicBufferProducer>& producer,
3399 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3400 uint32_t minLayerZ, uint32_t maxLayerZ,
3401 bool useIdentityTransform, Transform::orientation_flags rotation,
3402 bool isLocalScreenshot)
3403{
3404 ATRACE_CALL();
3405
3406 // get screen geometry
3407 uint32_t hw_w = hw->getWidth();
3408 uint32_t hw_h = hw->getHeight();
3409
3410 if (rotation & Transform::ROT_90) {
3411 std::swap(hw_w, hw_h);
3412 }
3413
3414 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3415 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3416 reqWidth, reqHeight, hw_w, hw_h);
3417 return BAD_VALUE;
3418 }
3419
3420 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3421 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3422
3423 bool secureLayerIsVisible = false;
3424 const LayerVector& layers(mDrawingState.layersSortedByZ);
3425 const size_t count = layers.size();
3426 for (size_t i = 0 ; i < count ; ++i) {
3427 const sp<Layer>& layer(layers[i]);
3428 const Layer::State& state(layer->getDrawingState());
3429 if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ &&
3430 state.z <= maxLayerZ && layer->isVisible() &&
3431 layer->isSecure()) {
3432 secureLayerIsVisible = true;
3433 }
3434 }
3435
3436 if (!isLocalScreenshot && secureLayerIsVisible) {
3437 ALOGW("FB is protected: PERMISSION_DENIED");
3438 return PERMISSION_DENIED;
3439 }
3440
3441 // create a surface (because we're a producer, and we need to
3442 // dequeue/queue a buffer)
3443 sp<Surface> sur = new Surface(producer, false);
3444 ANativeWindow* window = sur.get();
3445
3446 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3447 if (result == NO_ERROR) {
3448 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3449 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
3450
3451 int err = 0;
3452 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
3453 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
3454 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3455 err |= native_window_set_usage(window, usage);
3456
3457 if (err == NO_ERROR) {
3458 ANativeWindowBuffer* buffer;
3459 /* TODO: Once we have the sync framework everywhere this can use
3460 * server-side waits on the fence that dequeueBuffer returns.
3461 */
3462 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3463 if (result == NO_ERROR) {
3464 int syncFd = -1;
3465 // create an EGLImage from the buffer so we can later
3466 // turn it into a texture
3467 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3468 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3469 if (image != EGL_NO_IMAGE_KHR) {
3470 // this binds the given EGLImage as a framebuffer for the
3471 // duration of this scope.
3472 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3473 if (imageBond.getStatus() == NO_ERROR) {
3474 // this will in fact render into our dequeued buffer
3475 // via an FBO, which means we didn't have to create
3476 // an EGLSurface and therefore we're not
3477 // dependent on the context's EGLConfig.
3478 renderScreenImplLocked(
3479 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3480 useIdentityTransform, rotation);
3481
3482 // Attempt to create a sync khr object that can produce a sync point. If that
3483 // isn't available, create a non-dupable sync object in the fallback path and
3484 // wait on it directly.
3485 EGLSyncKHR sync;
3486 if (!DEBUG_SCREENSHOTS) {
3487 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
3488 // native fence fd will not be populated until flush() is done.
3489 getRenderEngine().flush();
3490 } else {
3491 sync = EGL_NO_SYNC_KHR;
3492 }
3493 if (sync != EGL_NO_SYNC_KHR) {
3494 // get the sync fd
3495 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3496 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3497 ALOGW("captureScreen: failed to dup sync khr object");
3498 syncFd = -1;
3499 }
3500 eglDestroySyncKHR(mEGLDisplay, sync);
3501 } else {
3502 // fallback path
3503 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3504 if (sync != EGL_NO_SYNC_KHR) {
3505 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3506 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3507 EGLint eglErr = eglGetError();
3508 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3509 ALOGW("captureScreen: fence wait timed out");
3510 } else {
3511 ALOGW_IF(eglErr != EGL_SUCCESS,
3512 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3513 }
3514 eglDestroySyncKHR(mEGLDisplay, sync);
3515 } else {
3516 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3517 }
3518 }
3519 if (DEBUG_SCREENSHOTS) {
3520 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3521 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3522 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3523 hw, minLayerZ, maxLayerZ);
3524 delete [] pixels;
3525 }
3526
3527 } else {
3528 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3529 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003530 window->cancelBuffer(window, buffer, syncFd);
3531 buffer = NULL;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003532 }
3533 // destroy our image
3534 eglDestroyImageKHR(mEGLDisplay, image);
3535 } else {
3536 result = BAD_VALUE;
3537 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003538 if (buffer) {
3539 // queueBuffer takes ownership of syncFd
3540 result = window->queueBuffer(window, buffer, syncFd);
3541 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003542 }
3543 } else {
3544 result = BAD_VALUE;
3545 }
3546 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3547 }
3548
3549 return result;
3550}
3551
3552void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3553 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
3554 if (DEBUG_SCREENSHOTS) {
3555 for (size_t y=0 ; y<h ; y++) {
3556 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3557 for (size_t x=0 ; x<w ; x++) {
3558 if (p[x] != 0xFF000000) return;
3559 }
3560 }
3561 ALOGE("*** we just took a black screenshot ***\n"
3562 "requested minz=%d, maxz=%d, layerStack=%d",
3563 minLayerZ, maxLayerZ, hw->getLayerStack());
3564 const LayerVector& layers( mDrawingState.layersSortedByZ );
3565 const size_t count = layers.size();
3566 for (size_t i=0 ; i<count ; ++i) {
3567 const sp<Layer>& layer(layers[i]);
3568 const Layer::State& state(layer->getDrawingState());
3569 const bool visible = (state.layerStack == hw->getLayerStack())
3570 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3571 && (layer->isVisible());
3572 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x",
3573 visible ? '+' : '-',
3574 i, layer->getName().string(), state.layerStack, state.z,
3575 layer->isVisible(), state.flags, state.alpha);
3576 }
3577 }
3578}
3579
3580// ---------------------------------------------------------------------------
3581
3582SurfaceFlinger::LayerVector::LayerVector() {
3583}
3584
3585SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
3586 : SortedVector<sp<Layer> >(rhs) {
3587}
3588
3589int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3590 const void* rhs) const
3591{
3592 // sort layers per layer-stack, then by z-order and finally by sequence
3593 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3594 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
3595
3596 uint32_t ls = l->getCurrentState().layerStack;
3597 uint32_t rs = r->getCurrentState().layerStack;
3598 if (ls != rs)
3599 return ls - rs;
3600
3601 uint32_t lz = l->getCurrentState().z;
3602 uint32_t rz = r->getCurrentState().z;
3603 if (lz != rz)
3604 return lz - rz;
3605
3606 return l->sequence - r->sequence;
3607}
3608
3609// ---------------------------------------------------------------------------
3610
3611SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
3612 : type(DisplayDevice::DISPLAY_ID_INVALID),
3613 layerStack(DisplayDevice::NO_LAYER_STACK),
3614 orientation(0),
3615 width(0),
3616 height(0),
3617 isSecure(false) {
3618}
3619
3620SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(
3621 DisplayDevice::DisplayType type, bool isSecure)
3622 : type(type),
3623 layerStack(DisplayDevice::NO_LAYER_STACK),
3624 orientation(0),
3625 width(0),
3626 height(0),
3627 isSecure(isSecure) {
3628 viewport.makeInvalid();
3629 frame.makeInvalid();
3630}
3631
3632// ---------------------------------------------------------------------------
3633
3634}; // namespace android
3635
3636
3637#if defined(__gl_h_)
3638#error "don't include gl/gl.h in this file"
3639#endif
3640
3641#if defined(__gl2_h_)
3642#error "don't include gl2/gl2.h in this file"
3643#endif