DisplayDevice.cpp revision 32341381c9493d7953e40f7f79653cfc52868863
1/*
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#include <stdlib.h>
18#include <stdio.h>
19#include <string.h>
20#include <math.h>
21
22#include <cutils/properties.h>
23
24#include <utils/RefBase.h>
25#include <utils/Log.h>
26
27#include <ui/DisplayInfo.h>
28#include <ui/PixelFormat.h>
29
30#include <gui/SurfaceTextureClient.h>
31
32#include <GLES/gl.h>
33#include <EGL/egl.h>
34#include <EGL/eglext.h>
35
36#include <hardware/gralloc.h>
37
38#include "DisplayHardware/FramebufferSurface.h"
39#include "DisplayHardware/HWComposer.h"
40
41#include "clz.h"
42#include "DisplayDevice.h"
43#include "GLExtensions.h"
44#include "SurfaceFlinger.h"
45#include "LayerBase.h"
46
47// ----------------------------------------------------------------------------
48using namespace android;
49// ----------------------------------------------------------------------------
50
51static __attribute__((noinline))
52void checkGLErrors()
53{
54    do {
55        // there could be more than one error flag
56        GLenum error = glGetError();
57        if (error == GL_NO_ERROR)
58            break;
59        ALOGE("GL error 0x%04x", int(error));
60    } while(true);
61}
62
63// ----------------------------------------------------------------------------
64
65/*
66 * Initialize the display to the specified values.
67 *
68 */
69
70DisplayDevice::DisplayDevice(
71        const sp<SurfaceFlinger>& flinger,
72        DisplayType type, const wp<IBinder>& displayToken,
73        const sp<ANativeWindow>& nativeWindow,
74        const sp<FramebufferSurface>& framebufferSurface,
75        EGLConfig config)
76    : mFlinger(flinger),
77      mType(type), mHwcDisplayId(-1),
78      mNativeWindow(nativeWindow),
79      mFramebufferSurface(framebufferSurface),
80      mDisplay(EGL_NO_DISPLAY),
81      mSurface(EGL_NO_SURFACE),
82      mContext(EGL_NO_CONTEXT),
83      mDisplayWidth(), mDisplayHeight(), mFormat(),
84      mFlags(),
85      mPageFlipCount(),
86      mSecureLayerVisible(false),
87      mScreenAcquired(false),
88      mLayerStack(0),
89      mOrientation()
90{
91    init(config);
92}
93
94DisplayDevice::~DisplayDevice() {
95    if (mSurface != EGL_NO_SURFACE) {
96        eglDestroySurface(mDisplay, mSurface);
97        mSurface = EGL_NO_SURFACE;
98    }
99}
100
101bool DisplayDevice::isValid() const {
102    return mFlinger != NULL;
103}
104
105int DisplayDevice::getWidth() const {
106    return mDisplayWidth;
107}
108
109int DisplayDevice::getHeight() const {
110    return mDisplayHeight;
111}
112
113PixelFormat DisplayDevice::getFormat() const {
114    return mFormat;
115}
116
117EGLSurface DisplayDevice::getEGLSurface() const {
118    return mSurface;
119}
120
121void DisplayDevice::init(EGLConfig config)
122{
123    ANativeWindow* const window = mNativeWindow.get();
124
125    int format;
126    window->query(window, NATIVE_WINDOW_FORMAT, &format);
127
128    /*
129     * Create our display's surface
130     */
131
132    EGLSurface surface;
133    EGLint w, h;
134    EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
135    surface = eglCreateWindowSurface(display, config, window, NULL);
136    eglQuerySurface(display, surface, EGL_WIDTH,  &mDisplayWidth);
137    eglQuerySurface(display, surface, EGL_HEIGHT, &mDisplayHeight);
138
139    mDisplay = display;
140    mSurface = surface;
141    mFormat  = format;
142    mPageFlipCount = 0;
143    mViewport.makeInvalid();
144    mFrame.makeInvalid();
145
146    // external displays are always considered enabled
147    mScreenAcquired = (mType >= DisplayDevice::NUM_DISPLAY_TYPES);
148
149    // get an h/w composer ID
150    mHwcDisplayId = mFlinger->allocateHwcDisplayId(mType);
151
152    // Name the display.  The name will be replaced shortly if the display
153    // was created with createDisplay().
154    switch (mType) {
155        case DISPLAY_PRIMARY:
156            mDisplayName = "Built-in Screen";
157            break;
158        case DISPLAY_EXTERNAL:
159            mDisplayName = "HDMI Screen";
160            break;
161        default:
162            mDisplayName = "Virtual Screen";    // e.g. Overlay #n
163            break;
164    }
165
166    // initialize the display orientation transform.
167    setProjection(DisplayState::eOrientationDefault, mViewport, mFrame);
168}
169
170void DisplayDevice::setDisplayName(const String8& displayName) {
171    if (!displayName.isEmpty()) {
172        // never override the name with an empty name
173        mDisplayName = displayName;
174    }
175}
176
177uint32_t DisplayDevice::getPageFlipCount() const {
178    return mPageFlipCount;
179}
180
181status_t DisplayDevice::compositionComplete() const {
182    if (mFramebufferSurface == NULL) {
183        return NO_ERROR;
184    }
185    return mFramebufferSurface->compositionComplete();
186}
187
188void DisplayDevice::flip(const Region& dirty) const
189{
190    checkGLErrors();
191
192    EGLDisplay dpy = mDisplay;
193    EGLSurface surface = mSurface;
194
195#ifdef EGL_ANDROID_swap_rectangle
196    if (mFlags & SWAP_RECTANGLE) {
197        const Region newDirty(dirty.intersect(bounds()));
198        const Rect b(newDirty.getBounds());
199        eglSetSwapRectangleANDROID(dpy, surface,
200                b.left, b.top, b.width(), b.height());
201    }
202#endif
203
204    mPageFlipCount++;
205}
206
207void DisplayDevice::swapBuffers(HWComposer& hwc) const {
208    EGLBoolean success = EGL_TRUE;
209    if (hwc.initCheck() != NO_ERROR) {
210        // no HWC, we call eglSwapBuffers()
211        success = eglSwapBuffers(mDisplay, mSurface);
212    } else {
213        // We have a valid HWC, but not all displays can use it, in particular
214        // the virtual displays are on their own.
215        // TODO: HWC 1.2 will allow virtual displays
216        if (mType >= DisplayDevice::DISPLAY_VIRTUAL) {
217            // always call eglSwapBuffers() for virtual displays
218            success = eglSwapBuffers(mDisplay, mSurface);
219        } else if (hwc.supportsFramebufferTarget()) {
220            // as of hwc 1.1 we always call eglSwapBuffers if we have some
221            // GLES layers
222            if (hwc.hasGlesComposition(mType)) {
223                success = eglSwapBuffers(mDisplay, mSurface);
224            }
225        } else {
226            // HWC doesn't have the framebuffer target, we don't call
227            // eglSwapBuffers(), since this is handled by HWComposer::commit().
228        }
229    }
230
231    if (!success) {
232        EGLint error = eglGetError();
233        if (error == EGL_CONTEXT_LOST ||
234                mType == DisplayDevice::DISPLAY_PRIMARY) {
235            LOG_ALWAYS_FATAL("eglSwapBuffers(%p, %p) failed with 0x%08x",
236                    mDisplay, mSurface, eglGetError());
237        }
238    }
239}
240
241void DisplayDevice::onSwapBuffersCompleted(HWComposer& hwc) const {
242    if (hwc.initCheck() == NO_ERROR) {
243        if (hwc.supportsFramebufferTarget()) {
244            int fd = hwc.getAndResetReleaseFenceFd(mType);
245            mFramebufferSurface->setReleaseFenceFd(fd);
246        }
247    }
248}
249
250uint32_t DisplayDevice::getFlags() const
251{
252    return mFlags;
253}
254
255EGLBoolean DisplayDevice::makeCurrent(EGLDisplay dpy,
256        const sp<const DisplayDevice>& hw, EGLContext ctx) {
257    EGLBoolean result = EGL_TRUE;
258    EGLSurface sur = eglGetCurrentSurface(EGL_DRAW);
259    if (sur != hw->mSurface) {
260        result = eglMakeCurrent(dpy, hw->mSurface, hw->mSurface, ctx);
261        if (result == EGL_TRUE) {
262            GLsizei w = hw->mDisplayWidth;
263            GLsizei h = hw->mDisplayHeight;
264            glViewport(0, 0, w, h);
265            glMatrixMode(GL_PROJECTION);
266            glLoadIdentity();
267            // put the origin in the left-bottom corner
268            glOrthof(0, w, 0, h, 0, 1); // l=0, r=w ; b=0, t=h
269        }
270    }
271    return result;
272}
273
274// ----------------------------------------------------------------------------
275
276void DisplayDevice::setVisibleLayersSortedByZ(const Vector< sp<LayerBase> >& layers) {
277    mVisibleLayersSortedByZ = layers;
278    mSecureLayerVisible = false;
279    size_t count = layers.size();
280    for (size_t i=0 ; i<count ; i++) {
281        if (layers[i]->isSecure()) {
282            mSecureLayerVisible = true;
283        }
284    }
285}
286
287const Vector< sp<LayerBase> >& DisplayDevice::getVisibleLayersSortedByZ() const {
288    return mVisibleLayersSortedByZ;
289}
290
291bool DisplayDevice::getSecureLayerVisible() const {
292    return mSecureLayerVisible;
293}
294
295Region DisplayDevice::getDirtyRegion(bool repaintEverything) const {
296    Region dirty;
297    if (repaintEverything) {
298        dirty.set(getBounds());
299    } else {
300        const Transform& planeTransform(mGlobalTransform);
301        dirty = planeTransform.transform(this->dirtyRegion);
302        dirty.andSelf(getBounds());
303    }
304    return dirty;
305}
306
307// ----------------------------------------------------------------------------
308
309bool DisplayDevice::canDraw() const {
310    return mScreenAcquired;
311}
312
313void DisplayDevice::releaseScreen() const {
314    mScreenAcquired = false;
315}
316
317void DisplayDevice::acquireScreen() const {
318    mScreenAcquired = true;
319}
320
321bool DisplayDevice::isScreenAcquired() const {
322    return mScreenAcquired;
323}
324
325// ----------------------------------------------------------------------------
326
327void DisplayDevice::setLayerStack(uint32_t stack) {
328    mLayerStack = stack;
329    dirtyRegion.set(bounds());
330}
331
332// ----------------------------------------------------------------------------
333
334status_t DisplayDevice::orientationToTransfrom(
335        int orientation, int w, int h, Transform* tr)
336{
337    uint32_t flags = 0;
338    switch (orientation) {
339    case DisplayState::eOrientationDefault:
340        flags = Transform::ROT_0;
341        break;
342    case DisplayState::eOrientation90:
343        flags = Transform::ROT_90;
344        break;
345    case DisplayState::eOrientation180:
346        flags = Transform::ROT_180;
347        break;
348    case DisplayState::eOrientation270:
349        flags = Transform::ROT_270;
350        break;
351    default:
352        return BAD_VALUE;
353    }
354    tr->set(flags, w, h);
355    return NO_ERROR;
356}
357
358void DisplayDevice::setProjection(int orientation,
359        const Rect& viewport, const Rect& frame) {
360    mOrientation = orientation;
361    mViewport = viewport;
362    mFrame = frame;
363    updateGeometryTransform();
364}
365
366void DisplayDevice::updateGeometryTransform() {
367    int w = mDisplayWidth;
368    int h = mDisplayHeight;
369    Transform TL, TP, R, S;
370    if (DisplayDevice::orientationToTransfrom(
371            mOrientation, w, h, &R) == NO_ERROR) {
372        dirtyRegion.set(bounds());
373
374        Rect viewport(mViewport);
375        Rect frame(mFrame);
376
377        if (!frame.isValid()) {
378            // the destination frame can be invalid if it has never been set,
379            // in that case we assume the whole display frame.
380            frame = Rect(w, h);
381        }
382
383        if (viewport.isEmpty()) {
384            // viewport can be invalid if it has never been set, in that case
385            // we assume the whole display size.
386            // it's also invalid to have an empty viewport, so we handle that
387            // case in the same way.
388            viewport = Rect(w, h);
389            if (R.getOrientation() & Transform::ROT_90) {
390                // viewport is always specified in the logical orientation
391                // of the display (ie: post-rotation).
392                swap(viewport.right, viewport.bottom);
393            }
394        }
395
396        float src_width  = viewport.width();
397        float src_height = viewport.height();
398        float dst_width  = frame.width();
399        float dst_height = frame.height();
400        if (src_width != dst_width || src_height != dst_height) {
401            float sx = dst_width  / src_width;
402            float sy = dst_height / src_height;
403            S.set(sx, 0, 0, sy);
404        }
405
406        float src_x = viewport.left;
407        float src_y = viewport.top;
408        float dst_x = frame.left;
409        float dst_y = frame.top;
410        TL.set(-src_x, -src_y);
411        TP.set(dst_x, dst_y);
412
413        // The viewport and frame are both in the logical orientation.
414        // Apply the logical translation, scale to physical size, apply the
415        // physical translation and finally rotate to the physical orientation.
416        mGlobalTransform = R * TP * S * TL;
417
418        const uint8_t type = mGlobalTransform.getType();
419        mNeedsFiltering = (!mGlobalTransform.preserveRects() ||
420                (type >= Transform::SCALE));
421    }
422}
423
424void DisplayDevice::dump(String8& result, char* buffer, size_t SIZE) const {
425    const Transform& tr(mGlobalTransform);
426    snprintf(buffer, SIZE,
427        "+ DisplayDevice: %s\n"
428        "   type=%x, layerStack=%u, (%4dx%4d), ANativeWindow=%p, orient=%2d (type=%08x), "
429        "flips=%u, secure=%d, acquired=%d, numLayers=%u\n"
430        "   v:[%d,%d,%d,%d], f:[%d,%d,%d,%d], "
431        "transform:[[%0.3f,%0.3f,%0.3f][%0.3f,%0.3f,%0.3f][%0.3f,%0.3f,%0.3f]]\n",
432        mDisplayName.string(), mType,
433        mLayerStack, mDisplayWidth, mDisplayHeight, mNativeWindow.get(),
434        mOrientation, tr.getType(), getPageFlipCount(),
435        mSecureLayerVisible, mScreenAcquired, mVisibleLayersSortedByZ.size(),
436        mViewport.left, mViewport.top, mViewport.right, mViewport.bottom,
437        mFrame.left, mFrame.top, mFrame.right, mFrame.bottom,
438        tr[0][0], tr[1][0], tr[2][0],
439        tr[0][1], tr[1][1], tr[2][1],
440        tr[0][2], tr[1][2], tr[2][2]);
441
442    result.append(buffer);
443
444    String8 fbtargetDump;
445    if (mFramebufferSurface != NULL) {
446        mFramebufferSurface->dump(fbtargetDump);
447        result.append(fbtargetDump);
448    }
449}
450